/// <reference path="jquery-1.3.2-vsdoc2.js"/>

// define eviivo.wls namespace (if not yet defined)
window.eviivo = window.eviivo || {};
eviivo.wls = eviivo.wls || {};

var delay = function(func) { setTimeout(func, 0); };
var delay500 = function (func) { setTimeout(func, 500); };
var delay1000 = function (func) { setTimeout(func, 1000); };

$(function () {

    if (isTsuEnvironment === false) {
        // Detail Page - non-TSU only: for handeling the Promotional Information Next and Previous functionality
        if ($('body').hasClass('page_details') || $('body').hasClass('page_instantweb')) {

            $('.offer_link_trigger').live('click', function (e) {
                e.preventDefault();
                var urlSections = this.href.split('#');
                var paramArray;
                if (urlSections.length == 2) {
                    paramArray = urlSections[1].split(',');
                }
                if (paramArray.length == 10) {


                    var shortName = paramArray[0];
                    var roomId = paramArray[1];
                    var industryType = paramArray[2];
                    var startDate = paramArray[3];
                    var endDate = paramArray[4];
                    var windowSizeInDay = paramArray[5];
                    var isNextButton = paramArray[6];
                    var referrerName = paramArray[7];
                    var contentId = paramArray[8];
                    var currencyCode = paramArray[9];


                    var serviceUrl = Eviivo$ServicesUrl + 'PromotionalInformationService.asmx/GetPromotionalInformation';
                    var paramData = '{"referrerName":"' + referrerName + '","shortName":"' + shortName + '","contentId":"' + contentId + '","roomId":"' + roomId + '","industryType":' + industryType + ',"startDate":"' + startDate + '","endDate":"' + endDate + '","windowSizeInDay":' + windowSizeInDay + ',"isNextButtonClicked":' + isNextButton + ',"currencyCode":"' + currencyCode + '"}';


                    var promotionalOffersMainContent = $('div.promotionalOffers_' + roomId);
                    var promotionalOffersNextButton = $('.next_offer_window_' + roomId);
                    var promotionalOffersPreviousButton = $('.previous_offer_window_' + roomId);
                    var promotionalOffersError = $('.promotionalOffers_error_' + roomId);
                    var promotionalOffersWindow = $('.promotionalOffers_window_' + roomId);
                    var promotionalOffersProgress = $('.promotionalOffers_Progress_' + roomId);
                    var promotionalOffersMainBody = $('.promotionalOffers_main_body_' + roomId);

                    promotionalOffersMainBody.css('visibility', 'hidden');
                    promotionalOffersProgress.show();

                    //turn off the error message if it is already on
                    if (false == promotionalOffersError.hasClass('hide_special_offer_element')) {
                        promotionalOffersError.addClass('hide_special_offer_element');
                    }

                    $.ajax({
                        type: 'POST', // the web service accepts POST requests only for security reasons
                        url: serviceUrl,
                        data: paramData, // need to pass data in JSON string
                        processData: false, // cannot process the data (it would be passed as a query string)
                        dataType: 'json', // want to get json results back
                        contentType: 'application/json', // data is passed in json format
                        success: function (json, textStatus) { // response handler
                            delay500(function () {
                                var response = json.d;
                                if (response.IsValid) {
                                    promotionalOffersMainContent.html(response.Offers);
                                    promotionalOffersWindow.html(response.AvailabilityDateRange);
                                    promotionalOffersNextButton.html(response.NextButtonUrl);
                                    promotionalOffersPreviousButton.html(response.PreviousButtonUrl);

                                    promotionalOffersProgress.hide();
                                    promotionalOffersMainBody.css('visibility', 'visible');
                                }
                                else {
                                    //invalid response 
                                    if (promotionalOffersError.hasClass('hide_special_offer_element')) {
                                        promotionalOffersError.removeClass('hide_special_offer_element');
                                    }
                                    promotionalOffersProgress.hide();
                                    promotionalOffersMainBody.css('visibility', 'visible');
                                }
                            }); // delay
                        }, // success
                        error: function (request, textStatus, errorThrown) {
                            //Display proper Error message 
                            if (promotionalOffersError.hasClass('hide_special_offer_element')) {
                                promotionalOffersError.removeClass('hide_special_offer_element');
                            }
                            promotionalOffersProgress.hide();
                            promotionalOffersMainBody.css('visibility', 'visible');
                        } // error
                    }); // .ajax
                } else {
                    //invalid parameters
                }

            });
        } //end of handeling the Promotional Information

        // Booking Summary page - Supplements Pop-Up
        if ($('body').hasClass('body_booking_summary')) {

            $('.supplement_remove_triger').click(function (e) {
                if (confirm(Eviivo.ScriptResources.confirmSupplementRemoval)) {
                    e.preventDefault();
                    var urlArray = this.href.split('#');
                    var paramArray = urlArray[1].split('~');
                    var supplementCode = paramArray[0];
                    var productIndex = paramArray[1];
                    $('#currentSupplementCode').val(supplementCode);
                    $('#currentProductIndex').val(productIndex);
                    __doPostBack('lnkBtnRemoveSupplement', '');
                }
            });

            function validateSupplementPopup() {
                var isValid = false;
                var errorMessage = "";
                var noExtraSelected = false;
                // When the button is "Change" (isSupplementAdded = true), and no options are selected, different validation text is displayed.
                var isSupplementAdded = ($('#simplemodal-data').find('.isSupplementAdded').length == 1);

                $('#simplemodal-data').find('.supplement_room').each(function () {

                    var supplement = $(this);
                    var nights = supplement.find('.checkbox_nights_selection').length;
                    var nightsSelected = supplement.find('input[type=checkbox]:checked').length;

                    if (supplement.find('input[type=checkbox]').length == supplement.find('input[type=checkbox]:disabled').length) {
                        // EVMYWEB-5238: When the supplement is "All Nights", all the checkboxes are disabled & checked 
                        // (No of checkboxes disabled & checked == no of checkboxes for that supplement)
                        // Thereby, giving no option for the user to select, in which case nights validation could be ignored.
                        nights = 0;
                    }

                    var quantityElements = supplement.find('.supplement_control');
                    var quantityChildElements = supplement.find('.supplement_control_child');
                    var quantityValue = quantityElements.length > 0 ? parseInt(quantityElements.val(), 0) : 0;
                    var quantityChildValue = quantityChildElements.length > 0 ? parseInt(quantityChildElements.val(), 0) : 0;

                    // if exists both the nights selection & the Quantity
                    if (nights > 0 && (quantityElements.length > 0 || quantityChildElements.length > 0)) {
                        // Quantity selected, either child/ adult
                        if (quantityValue > 0 || quantityChildValue > 0) {
                            if (nightsSelected > 0) {
                                //nights selected
                                isValid = true;
                            }
                            else {
                                // nights not selected.
                                isValid = false;
                                errorMessage = Eviivo.ScriptResources.valNoNightsSelected;
                            }
                        }
                        else {
                            if (nightsSelected > 0) {
                                // Occupancy (drop-down) not selected
                                isValid = false;
                                errorMessage = Eviivo.ScriptResources.valNoOccupancySelected;
                            }
                            else {
                                isValid = isValid || false;
                                noExtraSelected = true;
                            }
                        }

                    }
                    // If only Quantity/ Occupancy exists but not selected.
                    else if (quantityElements.length > 0 || quantityChildElements.length > 0) {
                        if (quantityValue > 0 || quantityChildValue > 0) {
                            isValid = true;
                        }
                        else {
                            isValid = isValid || false;
                            noExtraSelected = true;
                        }
                    }
                    // If only Nights (checkbox) exists but not selected.
                    else if (nights > 0) {
                        if (nightsSelected > 0) {
                            //nights selected
                            isValid = true;
                        }
                        else {
                            // nights not selected.
                            isValid = isValid || false;
                            noExtraSelected = true;
                        }
                    }

                    // If no quantity/ nights exists: Eg Fixed Supplement (Single Room availability)
                    else {
                        isValid = true;
                    }
                    // if validation fails, but not because of not any extra selected, break the loop and display the error message.
                    if (isValid == false && errorMessage != "") {
                        return false; // breaks the loop.
                    }
                });

                var errorElement = $('#simplemodal-data').find('.lblError');
                if (isValid == false) {
                    if (noExtraSelected == true && errorMessage == "") {
                        // If no extra is selected for all the rooms, then display the error message according to,
                        // if the supplement is changed or newly added.
                        if (isSupplementAdded == true) {
                            errorMessage = Eviivo.ScriptResources.valChangeNoExtrasSelected;
                        }
                        else {
                            errorMessage = Eviivo.ScriptResources.valNoExtrasSelected;
                        }
                    }
                    errorElement.addClass('error').html(errorMessage);
                } else {
                    errorElement.removeClass('error').html('');
                }
                return isValid;
            }

            // return the selected value of all dropdowns and checkboxes in an associative array
            // e.g. {'quantity_0_0':1,'quantity_0_1':0}
            function getSupplementPopupState() {
                var state = {};
                $('#simplemodal-data').find('select,input[type=checkbox]').each(function () {
                    state[this.name] = { 'value': $(this).val(), 'checked': this.checked };
                });
                return state;
            }

            // set the values based on the saved state
            function setSupplementPopupState(state) {
                if (state) {
                    for (var name in state) {
                        //EVMYWEB-5337 make all elements not-disabled so that values are passed to the server
                        $('[name=' + name + ']').val(state[name].value).attr('checked', state[name].checked);
                    }
                }
            }

            $('.supplement_modal_trigger').live('click', function (e) {
                e.preventDefault();
                var urlArray = this.href.split('#');
                var paramArray = urlArray[1].split('~');

                if (paramArray.length == 2) {

                    var code = paramArray[0];
                    var supplementIndex = paramArray[1];
                    var divElement = $('.supplement_modal_div_' + supplementIndex);
                    if ($('#currentSupplementCode')) {
                        $('#currentSupplementCode').val(code);
                    }
                    if ($('#currentSupplementIndex')) {
                        $('#currentSupplementIndex').val(supplementIndex);
                    }
                    divElement.modal({
                        // IE8 Fix = it cannot use the 'form' for .NET it has to use the default 'body' (appendTo: 'body',)
                        overlayId: 'supplements-overlay',
                        overlayClose: false,
                        escClose: false,
                        onShow: function () {
                            // fix the position to absolute
                            var modal = this;
                            var container = $('#simplemodal-container');
                            var top = container.position().top;
                            container.css('position', 'absolute').css('top', top).css('height', 'auto');
                            // remove the window resize handler and add a new one just to resize the overlay
                            $(window).unbind('resize.simplemodal').bind('resize.simplemodal', function () {
                                var w = modal.getDimensions();
                                modal.d.overlay.css({ height: w[0], width: w[1] });
                            });
                            // remove the style expression added for IE6 simulating the fixed position
                            if ($.browser.msie && $.browser.version == '6.0') {
                                modal.d.container[0].style.removeExpression('top');
                            }

                            // Ignore the enter key (for the checkbox element, as when pressed enter it's getting redirected to PayPal checkout)
                            $('#simplemodal-data input[type = checkbox]').unbind('keydown').bind('keydown', function (e) {
                                if (e.keyCode == 13) {
                                    e.preventDefault();
                                }
                            });

                            //EVMYWEB-5250: Set the focus on the first element based on the selectable elements in the Pop-up (first selectable element)
                            var element = $('#simplemodal-data select:enabled:visible:first');
                            if (element.length > 0) {
                                // For firefox browser, the "select" element requires both blur & focus.
                                element.blur(); // visually shows which element it is pointing to
                                element.focus(); // selects the default element (but not visually pointed)
                            }
                            else {
                                element = $('#simplemodal-data input[type = checkbox]:enabled:visible:first');
                                if (element.length > 0) {
                                    element.focus();
                                }
                                else {
                                    $('#simplemodal-data').find('.supplement_add').focus();
                                }
                            }

                            // add event to the add button
                            $('#simplemodal-data').find('.supplement_add').click(function () {
                                var isValid = validateSupplementPopup();
                                if (isValid === true) {
                                    var state = getSupplementPopupState();
                                    $.modal.close();
                                    setSupplementPopupState(state);
                                    __doPostBack('btnAddSupplement', '');
                                }
                            });
                            // add event to the cancel button
                            $('#simplemodal-data').find('.supplement_cancel').click(function () {
                                $.modal.close();
                            });
                        }
                    });
                }
            });
        } //end of handeling the Supplements

        // Search Results Page - non-TSU only:
        if ($('body').hasClass('page_searchresults')) {
            // find all thumbnail images and change the main image on mouse over
            $('.provider_image_thumbs img').live('mouseover', function () {
                // clear the active class from other thumbnails
                $(this).siblings('img').removeClass('thumb_active');
                // set the active class on the current thumbnail
                $(this).addClass('thumb_active');
                // copy the attributes from the thumbnail to the main image
                var img = $(this).parents('.provider_image_holder').children('a').children('img');
                img.attr('src', this.src);
                img.attr('alt', this.alt);
                img.attr('title', this.title);
            });

            // imagesPopup
            var imagesPopup = {
                // html template for the popup
                htmlTemplate: " \
<div style='display:none'> \
    <div class='popup-content'> \
	    <div class='popup-header'><a href='PROVIDER_LINK'>PROVIDER_NAME</a></div> \
	    <div class='popup-image-container'>&nbsp;</div> \
	    <div class='popup-navigation'> \
		    <span class='popup-index'></span> \
	        <div class='popup-next button_button'><div class='input'>&gt;&gt;</div></div> \
	        <div class='popup-prev button_button'><div class='input'>&lt;&lt;</div></div> \
	        <div class='popup-title'>&nbsp;</div> \
	        <div class='clear'></div> \
	    </div> \
	    <div class='popup-bottom'> \
            <div class='button_button'><a class='provider-link input' href='PROVIDER_LINK'>View more information</a></div> \
        </div> \
    </div> \
</div> \
",
                // currently selected provider's identifier
                identifier: null,
                // index of the currently selected image
                index: null,
                // temporary array to store the data for each identifier to prevent extra service calls
                data: [],
                init: function () {
                    $('.provider_image_link, .provider-images-link a').click(function (e) {
                        // prevent navigation
                        e.preventDefault();

                        // get the URL to the provider overview page
                        var url = this.href;
                        var identifier = this.id.substring(3); // remove "id_"
                        // set the popup identifier
                        imagesPopup.identifier = identifier;
                        // reset the index
                        imagesPopup.index = 0;

                        // get the provider name and decorator style
                        var results_provider = $(this).parents('.results_provider');
                        var providerNameElement = $('.provider_name a', results_provider);
                        var providerName = providerNameElement.html();

                        // format the template
                        var html = imagesPopup.htmlTemplate.replace(/PROVIDER_NAME/g, providerName).replace(/PROVIDER_LINK/g, url);

                        // check the temporary data storage...
                        if (imagesPopup.data[identifier] == null) {
                            // - call the web service to get the data
                            // using POST method and requesting JSON data (note the json parameter below)
                            // ... $.getJSON() method does an HTTP GET and not POST
                            var serviceUrl = Eviivo$ServicesUrl + 'ImageService.asmx/GetImages';
                            $.ajax({
                                type: 'POST', // the web service accepts POST requests only for security reasons
                                url: serviceUrl,
                                data: '{"contentId":"' + identifier + '","providerShortName":"' + identifier + '","industryType":' + $("#hdnIndustryType").val() + '}', // need to pass data in JSON string
                                processData: false, // cannot process the data (it would be passed as a query string)
                                dataType: 'json', // want to get json results back
                                contentType: 'application/json', // data is passed in json format
                                success: function (json, textStatus) { // response handler
                                    delay(function () {

                                        var images = [];
                                        for (var i in json.d.Images) {
                                            var item = json.d.Images[i];
                                            // Type is mandatory, Title is optional; will display only Type because there may be not enough room for both
                                            var title = (item.Type == null) ? '' : item.Type;
                                            images.push({ src: item.Src, title: title });
                                        }
                                        // save the data
                                        imagesPopup.data[identifier] = images;
                                        imagesPopup.create(html);
                                    }); // delay
                                } // success
                            }); // .ajax
                        } else {
                            // - load the popup with temp data
                            imagesPopup.create(html);
                        }


                    }); // .click
                },
                create: function (html) {
                    // create a modal dialog with the data
                    // http://www.ericmmartin.com/projects/simplemodal/
                    $(html).modal({
                        closeHTML: "<a href='#' title='" + Eviivo.ScriptResources.Close + "' class='popup-close'>x</a>",
                        //position: ["15%", ],
                        overlayId: 'images-overlay',
                        overlayClose: true,
                        containerId: 'images-popup',
                        onOpen: imagesPopup.open,
                        onShow: imagesPopup.show,
                        onClose: imagesPopup.close
                    });
                },
                open: function (dialog) {
                    // show the first image
                    imagesPopup.navigate(0);
                    // bind navigation controls
                    $('.popup-prev').click(function () {
                        imagesPopup.navigate(-1);
                    });
                    $('.popup-next').click(function () {
                        imagesPopup.navigate(1);
                    });

                    // fade in
                    dialog.overlay.fadeIn(200, function () {
                        dialog.container.fadeIn(200, function () {
                            dialog.data.fadeIn(200);
                        });
                    });
                },
                navigate: function (delta) {
                    var images = imagesPopup.data[imagesPopup.identifier];
                    var count = images.length;
                    var index = imagesPopup.index;
                    // show the first image?
                    if (isNaN(index)) {
                        index = 0;
                    }
                    // navigate to previous or next image
                    index = index + delta;
                    if (index < 0) {
                        index = count - 1;
                    }
                    if (index >= count) {
                        index = 0;
                    }

                    // get the image data
                    var item = images[index];
                    // format the title
                    var title = imagesPopup.formatTitle(index, count, item.title);
                    // change the image by setting the background image of the container
                    $('.popup-image-container').css('backgroundImage', 'url(' + item.src + ')');
                    // change the index
                    imagesPopup.index = index;
                },
                formatTitle: function (index, count, title) {
                    $('.popup-title').html(Eviivo.ScriptResources.PhotoOf.replace('{0}', index + 1).replace('{1}', count) + ' ' + title);
                },
                show: function (dialog) {
                },
                close: function (dialog) {
                    // fade out and close
                    dialog.data.fadeOut(200, function () {
                        dialog.container.fadeOut(200, function () {
                            dialog.overlay.fadeOut(200, function () {
                                $.modal.close();
                            });
                        });
                    });
                },
                error: function (xhr) {
                    alert(xhr.statusText);
                }
            };
            imagesPopup.init();

        } else if (($('body').hasClass('page_details') || $('body').hasClass('page_instantweb') || $('body').hasClass('body_booking_summary'))
            && $('.rooms_thumbs').length > 0) {
            // Overview page - non-TSU only:
            // find all thumbnail images and change the main image on mouse over
            $('.rooms_thumbs img').live('mouseover', function () {
                // clear the active class from other thumbnails
                $(this).siblings('img').removeClass('thumb_active');
                // set the active class on the current thumbnail
                $(this).addClass('thumb_active');
                // copy the attributes from the thumbnail to the main image
                var img = $(this).parents('.supplement_image').children('.product_image').children('img');
                img.attr('src', this.src);
                img.attr('alt', this.alt);
                img.attr('title', this.title);
            });
        }
        else if ($('body').hasClass('page_details')
            && $('.overview_thumbs').length > 0) {
            // Rooms tab, Supplement Images
            // find all thumbnail images and change the main image on mouse over
            $('.overview_thumbs img').live('mouseover', function () {
                // clear the active class from other thumbnails
                $(this).siblings('img').removeClass('thumb_active');
                // set the active class on the current thumbnail
                $(this).addClass('thumb_active');
                // copy the attributes from the thumbnail to the main image
                var img = $(this).parents('.provider_image').children('a').children('#providerImageOverview');
                img.attr('src', this.src);
                img.attr('alt', this.alt);
                img.attr('title', this.title);
            });
        } else if ($('body').hasClass('body_booking')) {
            // Booking page - non-TSU only:

            // find the payment type element
            if ($('#box_payment_details_bg').length > 0) {
                // handle events on changing the payment type
                $('#radioPaymentCard, .payment_select_cards img').bind('click', function () {
                    $('#radioPaymentCard')[0].checked = true;
                    // simulate click on the input box if clicked on images to trigger validation
                    if (this.tagName == 'IMG') {
                        $('#radioPaymentCard').click();
                    }
                    //EVMYWEB-5412: Display of the Header message according to the payment option selected.
                    // display different popup message for different payment type
                    $('.top_infomessage,#box_payment_details_bg,#panelPopup,#box_payment_logos_box').addClass('payment_type_cards').removeClass('payment_type_select payment_type_paypal payment_type_ivr');
                    $('#box_payment_logos_box').removeClass('payment_type_paypal');
                });
                $('#radioPayPal, .payment_select_paypal img').bind('click', function () {
                    $('#radioPayPal')[0].checked = true;
                    // simulate click on the input box if clicked on images to trigger validation
                    if (this.tagName == 'IMG') {
                        $('#radioPayPal').click();
                    }
                    //EVMYWEB-5412: Display of the Header message according to the payment option selected.
                    $('.top_infomessage, #box_payment_details_bg').addClass('payment_type_paypal').removeClass('payment_type_select payment_type_cards payment_type_ivr');
                    // display different popup message for different payment type
                    // shows "transfering to PayPal" message but not after Express Checkout... the radio button is disabled for Express Checkout
                    if ($('.required-payment-type :disabled').length == 0) {
                        $('#panelPopup,#box_payment_logos_box').addClass('payment_type_paypal');
                    }
                });
                $('#radioIvr, .payment_select_ivr img').bind('click', function () {
                    $('#radioIvr')[0].checked = true;
                    // simulate click on the input box if clicked on images to trigger validation
                    if (this.tagName == 'IMG') {
                        $('#radioIvr').click();
                    }
                    //EVMYWEB-5412: Display of the Header message according to the payment option selected.
                    $('.top_infomessage, #box_payment_details_bg').addClass('payment_type_ivr').removeClass('payment_type_select payment_type_cards payment_type_paypal');
                    $('#box_payment_logos_box').removeClass('payment_type_paypal');
                });
                // security code popup
                $('.what_is_this').hover(function () {
                    $(this).find('.what_is_wrapper').show();
                }, function () {
                    $(this).find('.what_is_wrapper').hide();
                });

                // modify validators if there is a payment method selection available
                if ($('div.box_payment_type').length > 0) {
                    var input = $('div.box_payment_type input:checked');
                    // don't need to worry about nulls, jQuery function always returns jQuery object
                    if (input.length > 0) {
                        // simulate clicking on the selected radio button
                        input.click();
                    }
                    // if payment type is visible but disabled, remove the event handlers (as latest, so that previous calls are called)
                    if ($('div.box_payment_type input:disabled').length > 0) {
                        $('#radioPayPal, .payment_select_paypal img').unbind();
                        $('#radioPaymentCard, .payment_select_cards img').unbind();
                        $('#radioIvr, .payment_select_ivr img').unbind();
                        $('.box_payment_type img').css('cursor', 'default');
                    }
                }

                // show the IVR popup if the page is reloaded (there's a reference)
                var paymentType = $('.required-payment-type :checked').val();
                if (paymentType === "radioIvr" && $('#ivr_reference').text().length > 0) {
                    eviivo.wls.ivr.showOnLoad();
                }
            }
        }

        if ($('body').hasClass('page_details') || $('body').hasClass('page_instantweb')) {

            //affect any division containg expandable_triger in css
            $('.expandable_triger').live('click', function () {
                var thisParent = $(this).parent();
                if (thisParent.hasClass('expanded')) {
                    thisParent.removeClass('expanded').addClass('collapsed');
                }
                else {
                    thisParent.removeClass('collapsed').addClass('expanded');
                }
            });

            // EVMYWEB-5670 expand special offers box when you click on the Special Offers jump link 
            $('#special_offer_trigger').live('click', function () {
                $('.special_offer_msg_list').removeClass('expanded collapsed').addClass('expanded');
            });

        }
        // Availability scripts - non-TSU only:
        if ($('body').hasClass('page_searchresults') || $('body').hasClass('page_details') || $('body').hasClass('page_instantweb')) {

            // add onclick and mouseover event handlers for:
            // - search results page rows (results_grid)
            // - provider availability rows (opts_table)
            var rows = $('div.results_grid tr.product_row, div.searchbox_myweb_results tr.opts_row_result');
            rows.click(function () {
                // remove the existing selected class
                $(this).parents('tbody').find('.selected').removeClass('selected');
                // add the selected class and select the option
                $(this).addClass('selected').find('input').attr('checked', true);
            });
            // ensure the table row with selected checkbox has selected classname (fix for browser back issue)
            rows.removeClass('selected').find(':checked').parents('tr').addClass('selected');
            // change the table row classname on hover
            $('div.results_grid tr.product_row, div.searchbox_myweb_results tr.opts_row_result').hover(function () {
                $(this).addClass('over');
            }, function () {
                $(this).removeClass('over');
            });

            // Popup with details:
            // NOTE: To ensure that a popup always overlays all elements, the popup is added the body element
            // (there's known issue with IE6 bleeding out dropdowns through popups and no effect of z-index)
            var popupElement = $('<div class="popup_wrapper"></div>').appendTo('body');
            popupElement.isOverLink = false;
            popupElement.isOverWrapper = false;
            var hidePopup = function () { // variable to hide popup 
                if (popupElement.isOverWrapper == false && popupElement.isOverLink == false) {
                    popupElement.hide().html();
                    // IE6 bugfix
                    $('form').removeClass('hide_selects');
                }
                else {
                    delay1000(hidePopup);
                }
            };
            // add onmouseover event handler for:
            // - room details
            // - supplement details
            $(".popup_trigger").hover(function () {
                var triggerElement = $(this);
                var contentElement = triggerElement.next(".popup_target");
                var pos = triggerElement.offset();
                popupElement.css({ "left": (pos.left + triggerElement.width() + 20) + "px", "top": (pos.top - contentElement.outerHeight() / 2) + "px" });
                popupElement.html(contentElement.html());
                popupElement.show();
                popupElement.isOverLink = true;
                // IE6 bugfix
                $('form').addClass('hide_selects');
            }, function () {
                popupElement.isOverLink = false;
                delay1000(hidePopup); // hide popup with delay 1000 miliseconds
            });

            $('.popup_close').live('click', function () {
                popupElement.isOverLink = false;
                popupElement.isOverWrapper = false;
                hidePopup();
            });

            // add the class 'display_block' when the popup has been moused over
            $('.popup_wrapper').mouseover(function () {
                $(this).addClass("display_block");
                popupElement.isOverWrapper = true;
            }).mouseout(function () {
                $(this).removeClass("display_block");
                popupElement.isOverWrapper = false;
            });
        }

    } // if(isTsuEnvironment === false)

    // SORTING:
    // redirect after sort order change
    // the trigger should be attached only to select controls (DropDownList in the ASPX page)
    $("select.sort_trigger").change(eviivo.wls.sort);

    //EVMYWEB-5603 select the nights field content on focus
    // .nights_input is used in SearchControl, ServicedAvailability and NonServicedAvailability
    // .i-nights is used on InstantWeb search control
    // .search_nig is used in SearchTopControl (TSU WPNSA branding)
    eviivo.wls.selectOnFocus($('#searchbox,#searchControl').find('.nights_input input,.i-nights input,.search_nig input'));

});           // $(function() {

(function(window) {
    eviivo.wls.sort = function () {
        // actual query string
        var url = self.document.location.search;
        //EVMYWEB-5492
        // change the leading question mark to '&' for easier replacement of parameters below
        url = url.replace("?", "&");
        // remove sort parameter if present
        url = url.replace(/&sort=(\d+)/i, '');
        //EVMYWEB-1780 - A change of Results Sort Order should take User to 1st page of Results
        // remove page parameter if present inorder to take User to 1st page of Results
        url = url.replace(/&page=(\d+)/i, '');
        // change the sort order
        //EVMYWEB-5513 add the query only if the value is not empty
        if(this.value !== "") {
            url = url + "&sort=" + this.value;
        }
        //EVMYWEB-5492
        // remove the first '&' with '?'
        // - using regular expression and not using a global flag will ensure only the first one is replaced
        url = url.replace(/&/, "?");

        //EVMYWEB-5513
        // if the query is empty (there's just the question mark), then remove if
        if(url === "") {
            var location = self.document.location;
            // e.g. http: + // + www.bookdirectrooms.com + /hotel/uk/
            self.document.location = location.protocol + "//" + location.hostname + location.pathname;
        } else {
            // otherwise
            // redirect with new query string that has new sort parameter
            self.document.location.search = url;
        }
    };
})(this);

//EVMYWEB-5603 select the nights field content on focus
// the trick here is that when you click and .select() is called on focus,
// focus happens before the click and so the selection is lost (by the click event)
// so the .select() needs to happen after click
(function () {
    eviivo.wls.selectOnFocus = function (obj) {
        $(obj).click(function() {
            $(this).select();
        });
    };
})();


//EVMYWEB-5744 IVR functions
(function () {
    eviivo.wls.ivr = {};

    var $webform_submit = null;

    var $show = function(data) {
        if(data) {
            $('#ivr_reference').text(data.IvrCode);
            $('#ivr_timeout').text(data.TimeoutMinutes);
        }
        $('#ivr_popup').modal({
            close: false,
            onShow: function () {
                // fix the position to absolute and height to auto
                var modal = this;
                var container = $('#simplemodal-container');
                var top = container.position().top;
                container.css('position', 'absolute').css('top', top).css('height', 'auto');
                // remove the window resize handler and add a new one just to resize the overlay
                $(window).unbind('resize.simplemodal').bind('resize.simplemodal', function () {
                    var w = modal.getDimensions();
                    modal.d.overlay.css({ height: w[0], width: w[1] });
                });
                // don't know why, but the overlay inline style is display:none, so show it
                modal.d.overlay.show();
                // remove the style expression added for IE6 simulating the fixed position
                if ($.browser.msie && $.browser.version == '6.0') {
                    modal.d.container[0].style.removeExpression('top');
                }
            },
            onOpen: function(dialog) {
                // fade in
                dialog.overlay.fadeIn(200, function () {
                    dialog.container.fadeIn(200, function () {
                        dialog.data.fadeIn(200);
                    });
                });
            }
        });
        $timer();
        $enableSubmit();
    };

    var $timer = function() {
        setTimeout("eviivo.wls.ivr.check();", 60*1000);
    };

    var $disableSubmit = function() {
        // disable the Complete Booking button so that it won't be clicked again
        $('#processBooking').addClass('processing').attr('disabled','disabled');

        // prevent the form from being submitted
        // NOTE: WebForm_OnSubmit is a global ASP.NET variable
        $webform_submit = WebForm_OnSubmit;
        WebForm_OnSubmit = function() {return false;};
    };

    var $enableSubmit = function() {
        // enable back the Complete Booking button so that it could be clicked again
        $('#processBooking').removeClass('processing').removeAttr('disabled');

        // revert the form submit method
        WebForm_OnSubmit = $webform_submit;
    };

    var $getReferrerQueryString = function(key)
    {
        var regex = new RegExp("[\\?&]" + key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]") + "=([^&#]*)","ig");
        var qs = regex.exec(document.referrer);
        return (qs == null) ? null : qs[1];
    };
        
    var $check = function(onsuccess) {
        //EVMYWEB-6282 use ServiceUrlMapped to keep application path with Url mapping
        var serviceUrl = Eviivo$ServicesUrlMapped + 'BookingService.asmx/CheckIvrStatus';
        //EVMYWEB-6282 add query string parameters from the referrer
        if(document.referrer) {
            var brandingStyle = $getReferrerQueryString("brandingstyle");
            var isInstantWeb = $getReferrerQueryString("isinstantweb");
            var param = '?';
            if(brandingStyle) {
                serviceUrl = serviceUrl + param + 'brandingstyle=' + brandingStyle;
                if(param === '?') {
                    param = '&';
                }
            }
            if(isInstantWeb) {
                serviceUrl = serviceUrl + param + 'isinstantweb=' + isInstantWeb;
                if(param === '?') {
                    param = '&';
                }
            }
        }

        $.ajax({
            type: 'POST', // the web service accepts POST requests only for security reasons
            url: serviceUrl,
            data: "{}", // no data, but must be JSON
            processData: false, // cannot process the data (it would be passed as a query string)
            dataType: 'json', // want to get json results back
            contentType: 'application/json', // data is passed in json format
            success: function (json, textStatus) { // response handler
                if(json && json.d) {
                    delay(function () {
                        onsuccess(json.d);
                    }); // delay
                } else {
                    // reload to show the error
                    self.document.location = self.document.location;
                }
            }, // success
            error: function (request, textStatus, errorThrown) {
                // an error has occurred; I was able to produce 500 Internal Server Error with session timeout or invalid request
                // will just try to reload the page in hope the server code will find what the issue is and handle it the usual way
                self.document.location = self.document.location;
            } // error
        }); // .ajax    
    
    };
    
    var $validate = function(data) {
        $('#ivr_status').hide();
        if(data.RedirectUrl && data.RedirectUrl.length > 0) {
            // redirect to
            // - booking confirmation page (success)
            // - booking details page (declined or failure)
            // - provider homepage (unrecoverable error)
            self.document.location = data.RedirectUrl;
        } else {
            $timer();
        }
    };

    var $validateOnDone = function(data) {
        // if there is no redirect, that means it's still processing
        if(data.RedirectUrl && data.RedirectUrl.length > 0) {
            $('#ivr_status').hide();
            // redirect to
            // - booking confirmation page (success)
            // - booking details page (declined or failure)
            // - provider homepage (unrecoverable error)
            self.document.location = data.RedirectUrl;
        } else {
            // not done
            $('#ivr_status').show();
        }
    };

    var $done = function() {
        $check($validateOnDone);
    };

    
    var $init = function() {
        $disableSubmit();

        $('#btnIvrDone').bind('click', $done);
    };
    
    eviivo.wls.ivr.showOnLoad = function() {
        $init();
        $show();
        $(window).scrollTop(0)
    };

    eviivo.wls.ivr.load = function() {

        $init();

        // create IVR reservation and get back a payment reference
        //EVMYWEB-6282 use ServiceUrlMapped to keep application path with Url mapping
        var serviceUrl = Eviivo$ServicesUrlMapped + 'BookingService.asmx/GetIvrBookingReference';
        var data = '{"customerDetails":{"Title":"' + $('#customerTitle').val().trim() + '",'
            + '"FirstName":"' + $('#firstName').val().trim() + '",'
            + '"LastName":"' + $('#lastName').val().trim() + '",'
            + '"AddressLine1":"' + $('#addressLine1').val().trim() + '",'
            + '"AddressLine2":"' + $('#addressLine2').val().trim() + '",'
            + '"AddressLine3":"' + $('#addressLine3').val().trim() + '",'
            + '"TownCity":"' + $('#city').val().trim() + '",'
            + '"CountyState":"' + $('#state').val().trim() + '",'
            + '"PostCode":"' + $('#postcode').val().trim() + '",'
            + '"CountryCode":"' + $('#countrySelect').val().trim() + '",'
            + '"Country":"' + $('#countrySelect option:selected').text().trim() + '",'
            + '"HomePhone": {"Number":"' + $('#homePhone').val().trim() + '"},'
            + '"Email":"' + $('#email').val().trim() + '",'
            + '"EmailConfirm":"' + $('#emailConfirm').val().trim() + '",'
            + '"ArrivalTime":"' + ($('#arrivalTimeB').attr('selectedIndex') > 0 ? $('#arrivalTimeB').val().trim() : '') + '",'
            // encode the " character (double quotes) to unicode, so that it doesn't conflict with the double quotes surrounding the text
            // the " is \u0022 and we need to add extra \ before it while the double quote needs to be encoded
            + '"SpecialRequirements":"' + $('#specialRequirements').val().trim().replace('"','\\u0022') + '",'
            // EVMYWEB-1134 - Customers are not being opted in to Marketing selections
            // NOTE: The screen says: Check here if you DON'T WANT to be opted in periodic email...
            // ...if not checked, then opt-in is positive
            + '"IsPeriodicEmail":' + ($('#allowPeriodicEmail').is(':checked') == false ? 'true': 'false') + ','
            + '"IsCrossEmail":' + ($('#allowCrossEmail').is(':checked') == false ? 'true': 'false')
            + '}}';

        $.ajax({
            type: 'POST', // the web service accepts POST requests only for security reasons
            url: serviceUrl,
            data: data, // need to pass data in JSON string
            processData: false, // cannot process the data (it would be passed as a query string)
            dataType: 'json', // want to get json results back
            contentType: 'application/json', // data is passed in json format
            success: function (json, textStatus) { // response handler
                if(json && json.d) {
                    delay(function () {
                        $show(json.d);
                    }); // delay
                } else {
                    // reload to show the error...
                    self.document.location = self.document.location;
                }
            }, // success
            error: function (request, textStatus, errorThrown) {
                // an error has occurred; I was able to produce 500 Internal Server Error with session timeout or invalid request
                // will just try to reload the page in hope the server code will find what the issue is and handle it the usual way
                self.document.location = self.document.location;
            } // error
        }); // .ajax
    };

    eviivo.wls.ivr.check = function() {
        $check($validate);
    };

    eviivo.wls.ivr.cancel = function() {
        return true;
    };
})();

Type.registerNamespace('Eviivo');


//JIRA:EVMYWEB-4176 - payment type validation
function valPaymentType_ClientValidate(source, arguments) {
    // check if any payment type is checked
    // NOTE: watch the casing, ASP.NET IsValid property starts with a capital I
    arguments.IsValid = $('.required-payment-type :checked').length > 0;
}

Eviivo.GetParent = function(element, parent) 
{
        //check if elemet is an id, get the element and if not found return null
        if(typeof(element) == 'string') {
            element = $get(element);
        }
        if (!element) {
            return null;
        }
        var elements=[];
        if(typeof(parent) != 'string' ) {
            while(element.parentNode) {
                element = element.parentNode;
                elements.unshift(element);
                if (element == parent) {
                    return elements;
                }
            }
        }
        else {
            parent = parent.toUpperCase();
            if (element.nodeName && element.nodeName.toUpperCase() == parent) {
                elements.unshift(element);
                return elements;
            }                
            while(element.parentNode) {
            element = element.parentNode;
            //EVMYWEB-4482 : Business Venues - [object HTMLDivElement] sometimes appends to URL when you select filters
            if (element.nodeName.toUpperCase() != 'DIV') {
                elements.unshift(element);
            }
                if (element.nodeName && element.nodeName.toUpperCase() == parent) {
                    return elements;
                }
            }
        } 
        return elements;
};

Eviivo.GetParentWithClass = function(element, className) 
{
        //check if elemet is an id, get the element and if not found return null
        if(typeof(element) == 'string') {
            element = $get(element);
        }
        if (!element) {
            return null;
        }
        var elements=[];
        if(typeof(parent) != 'string' ) {
            while(element.parentNode) {
                element = element.parentNode;
                elements.unshift(element);
                if (Sys.UI.DomElement.containsCssClass(element, className)) {
                    return elements;
                }
            }
        }
        else {
            if (element.nodeName && Sys.UI.DomElement.containsCssClass(element, className)) {
                elements.unshift(element);
                return elements;
            }                
            while(element.parentNode) {
                element = element.parentNode;
                elements.unshift(element);
                if (element.nodeName && Sys.UI.DomElement.containsCssClass(element, className)) {
                    return elements;
                }
            }
        } 
        return elements;
};

Eviivo.PageLinks = function(pageNumber) {
    var key = "page";
    var url = document.location.search;
    var pageParam = key + "=" + pageNumber;

    //Reg expression to detect ?Page= or &Page=
    var r = new RegExp("(&|\\?)" + key + "=[^\&]*");
    // Replace the Reg expression query with the new key value (Page=pageNumber)
    url = url.replace(r, "$1" + pageParam);
    
    //If the url does not have any "page" key then adding the key
    if (!url.match(r)) {
        url += (url.length > 0 ? '&' : '?') + pageParam;
    }
    
    self.document.location.search = url;
};

// JIRA: EVMYWEB-1652 - Add on-screen message informing the user that results are being updated when filters are applied
Eviivo.FilterManager = function(containerId, modalPopupId) {

    // container element that holds all filters
    this._container = $get(containerId);
    // no need to store the whole modulPopup object
    this._modalPopupId = modalPopupId;
    this._triggers = [];
    if(this._container && this._modalPopupId != '') 
    {
        // filters are triggered by links inside the container, or checboxes inside links
        var links = this._container.getElementsByTagName('a');
        for(var i=0;i<links.length;i++) {
            var trigger = links[i];
            this._triggers.push(trigger);
            $addHandlers(trigger, { "click": this._onClick }, this);
        }
    }
};

Eviivo.FilterManager.prototype = {

    _onClick: function(e) {
        var target = e.target;

	    // need to add some delay so that it doesn't flicker when the page loads too quickly
	    // also have to pass the modal popup ID, can't use the element object
        setTimeout("$find('"+this._modalPopupId+"').show();", 100);

        // if the target is A link, redirect to href
        // otherwise, need to find A link in parent elements
        self.document.location = (target.tagName == 'A') ? target.href : Eviivo.GetParent(target, 'A');

        // redirect is handled with this script, do not proceed with normal link redirect
        return false;
    },

    dispose:function() {
        //clear handlers
        for(var i=0;i<this._triggers.length;i++) {
            $clearHandlers(this._triggers[i]);  
        }

        this._container = null;
        this._modalPopupId = null;
        this._triggers = null;
    }
};

Eviivo.FilterManager.registerClass('Eviivo.FilterManager', null, Sys.IDisposable);

Eviivo.FilterManager.create = Eviivo$FilterManager$create = function(containerId, modalPopupId) {
    Sys.Application.add_load(function() {
        Eviivo.FilterManager.Instance = new Eviivo.FilterManager(containerId, modalPopupId);
    });
};

//EVMYWEB-1651 - Add message saying "we are processing your payment please don't click back" after compelte booking button is pressed
Eviivo.BookNow = function (modalPopupId) {
    setTimeout("$find('" + modalPopupId + "').show();", 200);
    return true;
};

Eviivo.SetImage = function(sourceElement, targetImgId, imageSrc)
{
    targetElement = $get(targetImgId);    
    var thumbs = sourceElement.parentNode.getElementsByTagName('IMG');
    for (var i = 0;i < thumbs.length; i++)
    {        
        Sys.UI.DomElement.removeCssClass(thumbs[i], 'selected_thumb');
    }
    if (imageSrc)
    {
        targetElement.src = imageSrc;
    }
    else
    {
        targetElement.src = sourceElement.src;    
    }
    targetElement.alt = sourceElement.alt;
    targetElement.title = sourceElement.title;
    Sys.UI.DomElement.addCssClass(sourceElement, 'selected_thumb');
};

Eviivo.OpenW = function(loc) {
    window.open(loc,'popup','left=20,top=20,width=800,height=420,toolbar=0,resizable=0,scrollbars=yes');
};
Eviivo.OpenRoomW = function(loc) {
    window.open(loc, 'popup', 'left=20,top=20,width=800,height=650,toolbar=0,resizable=1,scrollbars=yes');
};

Eviivo.OpenWF = function(loc) {
    window.open(loc,'popup','left=20,top=20,width=800,toolbar=0,resizable=0,scrollbars=yes');
};

Eviivo.OpenWP = function(loc) {
    window.open(loc,'popup','left=20,top=20,width=620,height=420,toolbar=0,resizable=1,scrollbars=yes');
};

Type.registerNamespace("IndustryType");

IndustryType = function() { };
IndustryType.prototype =
{
    Serviced: 1,
    NonServiced: 9,
    TEA: 13,
    Events: 3,
    Activities: 5,
    BusinessVenues: 6,
    EatingAndDrinking: 7
};
IndustryType.registerEnum("IndustryType");

Type.registerNamespace('Eviivo.Search');

//EVMYWEB-3228: SEO/Conversion: add sections to typehead list (rel 21)
Eviivo.Search.IndustryType = null;
Eviivo.Search.IndustrySubType = null;
Eviivo.Search.ControlId = null;
Eviivo.Search.HiddenProviderIdentifierId = null;

Eviivo.Search.FindIndustryType = function () {
    var container = $(Eviivo.Search.ControlId);
    if (container) {
        if (container.hasClass('searchTypeServiced')) {
            Eviivo.Search.IndustryType = IndustryType.Serviced;
            Eviivo.Search.IndustrySubType = 1; // Hotels by default; necessary for TSU, ignored by non-TSU
        } else if (container.hasClass('searchTypeNonServiced')) {
            Eviivo.Search.IndustryType = IndustryType.NonServiced;
            Eviivo.Search.IndustrySubType = 0;
        } else if (container.hasClass('searchTypeEvents')) {
            Eviivo.Search.IndustryType = IndustryType.Events;
            Eviivo.Search.IndustrySubType = 0;
        } else if (container.hasClass('searchTypeTea')) {
            //EVMYWEB-5522
            // It is quite anoying to put such code here, but since the LocationServiceProxy.asmx web service
            // doesn't know anything about branding settings, so that it cannot know that a current referrer
            // supports a separate Activities search, or it does not 
            // a javascript code here needs to determine whether an attraction search (IndustryType.TEA)
            // should search for attractions and also for activities (IndustrySubType = 0) - e.g. on VisitBritain
            // or for attractions only (IndustrySubType = TEA) - e.g. on VisitWales
            Eviivo.Search.IndustryType = IndustryType.TEA;
            Eviivo.Search.IndustrySubType = 0;
            // try to find the activity radio button - this would mean that a separate activities search is supported
            if (container.find("div.searchbox_radio_activities").length > 0) {
                Eviivo.Search.IndustrySubType = 4; // IndustrySubType.TEA
            }
        } else if (container.hasClass('searchTypeActivities')) {
            Eviivo.Search.IndustryType = IndustryType.Activities;
            Eviivo.Search.IndustrySubType = 0;
        } else if (container.hasClass('searchTypeServicedHotels')) {
            Eviivo.Search.IndustryType = IndustryType.Serviced;
            Eviivo.Search.IndustrySubType = 2;
        } else if (container.hasClass('searchTypeServicedHolidayParks')) {
            Eviivo.Search.IndustryType = IndustryType.Serviced;
            Eviivo.Search.IndustrySubType = 3;
        } else if (container.hasClass('searchTypeBusinessVenues')) {
            Eviivo.Search.IndustryType = IndustryType.BusinessVenues;
            Eviivo.Search.IndustrySubType = 0;
        } else if (container.hasClass('searchTypeEatingAndDrinking')) {
            Eviivo.Search.IndustryType = IndustryType.EatingAndDrinking;
            Eviivo.Search.IndustrySubType = 0;
        } else {
            Eviivo.Search.IndustryType = 0;
            Eviivo.Search.IndustrySubType = 0;
        }
    }
};

//JIRA:EVMYWEB-4080 - specific provider identifier has been selected in the dropdown
Eviivo.Search.SetHiddenProviderIdentifier = function(value) {
    // jQuery never returns null so no need to check if the control is found or exists
    $(Eviivo.Search.HiddenProviderIdentifierId).val(value);
};

Type.registerNamespace('Eviivo.Layout');

// Container class name is controlled by values of control elements.
// This allows to handle visibility of all elements inside of the container
// using CSS when some control element event is triggered.
// How this works:
// - containerID is a container element id
// - controlsIDs is an associative array of control elements (not an array in [])
//   e.g. {'elementId1':'class1', 'elementId2':'class2', 'elementId3':'class3'}
// - onLayoutChanged is an optional function called after layout has been changed
// When a control event occurs then the class name is generated according to that control.
// Then the class name is assigned to the contanier (removing old class name previously assigned)
Eviivo.Layout = function Eviivo$Layout(containerID, controlsIDs, onLayoutChanged) {

    /// <summary locid="M:J#Eviivo.Layout" />
    /// <param name="containerID" type="String"></param>
    /// <param name="controlsIDs" type="Object"></param>
    /// <param name="onLayoutChanged" type="Object"></param>
    /// <returns type="Function"></returns>
    var e = Function._validateParams(arguments, [
        { name: "containerID", type: String },
        { name: "controlsIDs", type: Object },
        { name: "onLayoutChanged", type: Object, mayBeNull: true, optional: true }
    ]);
    if (e) throw e;

    var element = $get(containerID);
    if (!element) throw e;

    Eviivo.Layout.initializeBase(this, [element]);

    // Properties
    this._controlHandler = Function.createDelegate(this, this.controlClickedHandler);
    this._onLayoutChanged = onLayoutChanged || null;
    this._previousClassNameModifier = null;

    this._controls = [];
    for (var key in controlsIDs) {
        // array key = control ID
        var control = $get(key);
        if (control) {
            this._controls.push(control);
            // array value = class name
            var classModifier = controlsIDs[key];
            control.classNameModifier = classModifier;

            if (control.tagName == 'INPUT' && control.type == 'radio') {
                // handle click event for radio buttons
                control.eventName = 'click';
                $addHandler(control, 'click', this._controlHandler);
                if (control.checked == true) {
                    // setup the layout for checked radio button
                    this.controlClicked(control);
                    this._previousClassNameModifier = this.getClassModifier(control);
                } else {
                    // remove old initial class names
                    Sys.UI.DomElement.removeCssClass(element, this.getClassModifier(control));
                }
            } else if (control.tagName == 'SELECT') {
                // handle change event for dropdown menus
                control.eventName = 'change';
                $addHandler(control, 'change', this._controlHandler);
                this.controlClicked(control);
                this._previousClassNameModifier = this.getClassModifier(control);
            } else if (control.tagName == 'A' || control.tagName == 'SPAN') {
                // handle click event for links
                control.eventName = 'click';
                $addHandler(control, 'click', this._controlHandler);
                this.controlClicked(control);
                this._previousClassNameModifier = this.getClassModifier(control);
            }
        }
    }

    this.initialize();
};

Eviivo.Layout.prototype = {

    initialize: function Eviivo$Layout$initialize() {

        Eviivo.Layout.callBaseMethod(this, 'initialize');
    },

    dispose: function Eviivo$Layout$dispose() {
        if (this._controls) {
            for (var i = 0; i < this._controls.length; i++) {
                $removeHandler(this._controls[i], this._controls[i].eventName, this._controlHandler);
            }
        }
        this._controls = null;
        this._controlHandler = null;
        this._previousClassNameModifier = null;
        this._onLayoutChanged = null;

        Eviivo.Layout.callBaseMethod(this, 'dispose');
    },

    get_controls: function Eviivo$Layout$get_controls(index) {
        return this._controls[index];
    },

    getClassModifier: function Eviivo$Layout$getClassModifier(control) {
        // for drop down menus add selected value to the class name
        if (control.tagName == 'SELECT') {
            return control.classNameModifier + control.value;
        } else {
            return control.classNameModifier;
        }
    },

    controlClickedHandler: function Eviivo$Layout$controlClickedHandler(e) {
        this.controlClicked(e.target);
        if (e.target.tagName == 'A' || e.target.tagName == 'SPAN') {
            e.preventDefault();
            e.stopPropagation();
        }
    },

    controlClicked: function Eviivo$Layout$controlClicked(control) {
        // JIRA: EVMYWEB-1386 - Tabbed search control
        // if the click handler is initiated by click on label, use the control the label is for
        if (control.tagName == 'LABEL' && control.htmlFor) {
            control = $get(control.htmlFor);
        }
        var container = this.get_element();
        if (this._previousClassNameModifier && Sys.UI.DomElement.containsCssClass(container, this._previousClassNameModifier)) {
            Sys.UI.DomElement.removeCssClass(container, this._previousClassNameModifier);
        }
        var classModifier = this.getClassModifier(control);
        Sys.UI.DomElement.addCssClass(container, classModifier);
        this._previousClassNameModifier = classModifier;
        this.layoutChangedHandler();
    },

    layoutChangedHandler: function Eviivo$Layout$layoutChangedHandler() {
        if (this._onLayoutChanged) {
            this._onLayoutChanged(this);
        }
    }
};

Eviivo.Layout.registerClass('Eviivo.Layout', Sys.UI.Behavior, Sys.IDisposable);

Eviivo.Layout.create = Eviivo$Layout$create = function(containerID, controlsIDArray, onLayoutChanged) {
    Sys.Application.add_load(function() {
        new Eviivo.Layout(containerID, controlsIDArray, onLayoutChanged);
    });
};

// This function changes the style of elements that are used to put search top control in place.
Eviivo.FixTopSearch = function(layout) {
    var searchContainer = $get('searchbox_top');
    // get class name according to number of rooms
    var roomsClass = layout.getClassModifier(layout.get_controls(0));
    // NOTE: only one class name is used, not necessary to use Sys.UI.DomElement.addCssClass
    searchContainer.className = roomsClass;
    
    var browserClass =  'browser_'+Sys.Browser.name.toLowerCase();
    if(Sys.UI.DomElement.containsCssClass(searchContainer, browserClass) === false) {
        Sys.UI.DomElement.addCssClass(searchContainer, browserClass);
    }
};

//JIRA:EVMYWEB-4047 industry specific titles
// This function changes the location watermark text according to the selected industry type
Eviivo.UpdateWatermarkText = function() {
    var watermark = $find('locationWatermark');
    if (watermark) {
        Eviivo.Search.FindIndustryType();
        var text = watermark.get_WatermarkText();
        switch (Eviivo.Search.IndustryType) {
            case IndustryType.TEA:
                text = Eviivo.ScriptResources.LocationWatermarkAttractionsText;
                break;
            case IndustryType.Events:
                text = Eviivo.ScriptResources.LocationWatermarkEventsText;
                break;
            case IndustryType.Activities:
                text = Eviivo.ScriptResources.LocationWatermarkActivitiesText;
                break;
            case IndustryType.BusinessVenues:
                text = Eviivo.ScriptResources.LocationWatermarkVenuesText;
                break;
            case IndustryType.EatingAndDrinking:
                text = Eviivo.ScriptResources.LocationWatermarkEatingAndDrinking;
                break;
            default:
                text = Eviivo.ScriptResources.LocationWatermarkText;
                break;
        }
        watermark.set_WatermarkText(text);
    }
};

Eviivo.Search.SwapTemp = function(ele, stylename, before, after) {
    if (ele.value == before) { 
        AddStylesheet(stylename);
    ele.value = after;
    } else {
        RemoveStylesheet(stylename);
        ele.value = before;
    }
};



Eviivo.FlipImage = function (imgElementID, headerElementID, descriptionElementID, thumbBlockElementID) {
    this._currentImageIndex = 0;
    //create list of all thumbs elements
    this._imageList = $('.thumb');
    this._imageMain = $(imgElementID);
    this._header = $(headerElementID);
    this._description = $(descriptionElementID);
    this._count = this._imageList.length;
};

Eviivo.FlipImage.prototype = {

    previousImage: function () {
        this.setMainImage(--this._currentImageIndex);
    },

    nextImage: function () {
        this.setMainImage(++this._currentImageIndex);
    },

    setMainImage: function (index, urlRoom) {
        if (index < 0) {
            index = this._count - 1;
        }
        else if (index >= this._count) {
            index = 0;
        }
        //EVMYWEB-3620
        var imageCurrent = $(this._imageList[index]);
        var description = imageCurrent.attr('title');
        var imageData = $('#providerThumbData' + index);
        var src = imageData.attr('src');
        var title = imageData.attr('title');

        // set image as background of the viewport div
        this._imageMain.css("backgroundImage", "url(" + src + ")");
        if (isTsuEnvironment == false) {
            this._header.html(title);
        }

        this._imageList.removeClass('selected_thumb');

        imageCurrent.addClass('selected_thumb');

        if (description.length === 0) {
            this._description.html("&nbsp;");
        }
        else {
            this._description.html(description);
        }

        //EVMYWEB-3620: Images
        var paginationIndexEl = $('#photoIndex');
        var indexNew = 0;

        indexNew = index;
        ++indexNew;

        this._currentImageIndex = index;
        paginationIndexEl.html(indexNew);

        if (typeof (urlRoom) != 'undefined') {
            $('#roomUrl').attr('href', urlRoom);
            $('#roomUrl').show();
            //EVMYWEB-4015: Open Rooms tab when clicking a product image in the photo gallery
            $('#img_viewportLoader').addClass('pointer');
            this._imageMain.click(function () { window.location = urlRoom; });
        }
        else {
            $('#roomUrl').hide();
            this._imageMain.unbind('click');
            $('#img_viewportLoader').removeClass('pointer');
        }

        if ($('#previousIndexField').length > 0 && $('#nextIndexField').length > 0) {
            $('#previousIndexField').val(index == 0 ? this._count - 1 : index - 1);
            $('#nextIndexField').val((parseInt(index) + 1) % this._count);
        }

        //EVMYWEB-6044
        // determine the position of the selected thumbnail in the thumbnail area and scroll
        // so that the selected thumbnail is always in the view
        var thumbWidth = $('#thumb_frame').find('img:eq(0)').width();
        $('#thumb_frame').animate({scrollLeft: (thumbWidth * index) + 'px'}, 'fast', 'linear');
    },

    dispose: function () {
        this._imageList = null;
        this._imageMain = null;
        this._header = null;
        this._description = null;
    }
};

Eviivo.FlipImage.registerClass('Eviivo.FlipImage', null);

Date.prototype.addDays = function Date$addDays(days) {
    return new Date(this.getTime() + days*24*60*60*1000);
};

Eviivo.CheckIn = function(formats, startDateID, durationID, endDateID, calendarID) {

    var e = Function._validateParams(arguments, [
        {name: "formats", type: String},
        {name: "startDateID", type: String},
        {name: "durationID", type: String},
        {name: "endDateID", type: String},
        {name: "calendarID", type: String}
    ]);
    if (e) throw e;
    
    this._dateFormats = formats;
    this._startDate = Date.Now;
    this._duration = 0;        

    this._startE = $get(startDateID);
    if (this._startE)
    {
        this._startDate = Date.parseInvariant(this._startE.value, formats);    
        $addHandlers(this._startE, 
            {
                "blur" : this._onStartBlur
            },
            this);
    }
    
    this._durationE = $get(durationID);
    if (this._durationE)
    {
        $addHandlers(this._durationE, 
        {
            "blur" : this._onDurationBlur
        },
        this);
    }    
  
    this._endDate = $get(endDateID);

    this._calendarE = $find(calendarID);
    if (this._calendarE)
    {
        // register delegate for the calendar selected date changed.
        this.calDateSelected = Function.createDelegate(this,this._calDateSelected); 

        // attach to calendar extender date selection changed event
        this._calendarE.add_dateSelectionChanged(this.calDateSelected);
    }    
};

Eviivo.CheckIn.prototype = {    
    _onStartBlur : function(e) {
        if (e.target.value.length > 0) {
            //validate the input and calculate the end date
            var checkInDate = Date.parseInvariant(e.target.value, this._dateFormats);
            if (checkInDate)
            {
                //Update the start date
                this._startDate = checkInDate;
                this._updateEndDate();
            }
        }
    },
    
    _onDurationBlur : function(e) {
        if (e.target.value.length > 0) {
            //validate the duration and caluclate the end date
            var duration = parseInt(e.target.value, 10);
            if (!isNaN(duration))
            {         
                this._duration = duration;                
                this._updateEndDate();
            }
        }
    },
    
    _calDateSelected : function(e) {
        //Update the start date
        this._startDate = e.get_selectedDate();
        this._updateEndDate();
    },
    
    _updateEndDate : function() {
        //take the start date, add the duration and set the end date value
        if(this._startDate && this._endDate) {
            var endDate = this._startDate.addDays(this._duration);
            this._endDate.innerHTML = endDate.format('dd/MM/yyyy');
        }
    },
    
    dispose: function() {
        if(this._calendarE) {
            this._calendarE.remove_dateSelectionChanged(this.calDateSelected);
        }
        $clearHandlers(this._durationE);
        $clearHandlers(this._startE);
        $clearHandlers(this);
        Eviivo.CheckIn.callBaseMethod(this, 'dispose');
    }       
};

Eviivo.CheckIn.registerClass('Eviivo.CheckIn', null, Sys.IDisposable);

Eviivo.CheckIn.Create = function(formats, startDateID, durationID, endDateID, calendarID) {
    Sys.Application.add_load(function() {
        new Eviivo.CheckIn(formats, startDateID, durationID, endDateID, calendarID);
    });
};

Eviivo.AssociateDate = function(format, calendarID, associatedCalendarID, endDateID) {

    var e = Function._validateParams(arguments, [
        {name: "format", type: String},
        {name: "calendarID", type: String},
        {name: "associatedCalendarID", type: String},
        {name: "endDateID", type: String}
    ]);
    if (e) throw e;
    
    this._dateFormat = format;
    this._startDate = Date.Now;
      
    this._endControl = $get(endDateID);
    this._calendarControl = $find(calendarID);
    this._associatedCalendarControl = $find(associatedCalendarID);
    if (this._calendarControl && this._associatedCalendarControl)
    {
        // register delegate for the calendar selected date changed.
        this.calDateSelected = Function.createDelegate(this, this._calDateSelected); 

        // attach to calendar extender date selection changed event
        this._calendarControl.add_dateSelectionChanged(this.calDateSelected);
    }    
};

Eviivo.AssociateDate.prototype = {
    
    _calDateSelected : function(e) {
        //Update the start date
        this._startDate = e.get_selectedDate();
        this._updateEndDate();
    },
    
    _updateEndDate : function() {
        //if start date has changed, and end date is not defined or is less than new start date, set end date = start date
        if(this._startDate && this._endControl)
        {
            var endDate = Date.parseInvariant(this._endControl.value, this._dateFormat);
            
            if(!endDate || endDate < this._startDate) {
                this._associatedCalendarControl.set_selectedDate(this._startDate);
            }
        }
    },
    
    dispose: function() {
        if(this._calendarControl) {
            this._calendarControl.remove_dateSelectionChanged(this.calDateSelected);
        }
        $clearHandlers(this);
        Eviivo.AssociateDate.callBaseMethod(this, 'dispose');
    }       
};

Eviivo.AssociateDate.registerClass('Eviivo.AssociateDate', null, Sys.IDisposable);

Eviivo.AssociateDate.Create = function(formats, calendarID, associatedCalendarID, endDateID) {
    Sys.Application.add_load(function() {
        new Eviivo.AssociateDate(formats, calendarID, associatedCalendarID, endDateID);
    });
};

Eviivo.Availability = function(buttonID, durationID, roomID, consumerIDList, errrorDivID) {
    //button to validate on
    //date can not be null and is today or future
    //nights can not be null and is > 0
    //rooms is drop down
    //consumer[] total > 0 for each consumer inside the room index.
    this._button = $get(buttonID);
    this._errorDiv = $get(errrorDivID);
    this._duration = $get(durationID);
    this._room = $get(roomID);
    this._consumerIDList = consumerIDList;
    this._errorList = [];
    
    if(this._button) 
    {
        $addHandlers(this._button, { "click": this._onClick }, this);
    }
};

Eviivo.Availability.prototype = {

    _onClick:function(e) {
        this._errorDiv.innerHTML = '';
        this._errorList = [];
        if (!this._errorList.length > 0)
        {
            this._errorDiv.innerHTML = 'We had an error';
            e.stopPropagation();
        }
    },
    
    _validate:function(){
        this._errorList[0] = 'error';
        
    },
    
    getRoomTotal:function(roomNumber) {
        return  getNumber(this._consumerIDList[roomNumber].Adult) + getNumber(this._consumerIDList[roomNumber].Child) + getNumber(this._consumerIDList[roomNumber].Con);
    },
    
    getNumber:function(elemID){
        if (elemID)
        {   var elem = $get(elemID);
            if (elemID && !isNan(elemID.innerHTML))
            {
                return parseInt(elemID.HTML, 10);
            }   
        }
        return 0;
    },        
    
    dispose:function() {
        //clear handlers
        $clearHandlers(this._button);  
        Eviivo.Availability.callBaseMethod(this, 'dispose');
    }
};

Eviivo.Availability.registerClass('Eviivo.Availability', null, Sys.IDisposable);

Eviivo.ToggleLink = function(text, altText) {    
    this._text = text;
    this._altText = altText;
};
Eviivo.ToggleLink.Instance = null;
Eviivo.ToggleLink.Toggle = function(e, src, targetID) {
    if(Eviivo.ToggleLink.Instance) {
        Eviivo.ToggleLink.Instance.toggle(e, src, targetID);
    }
    return false;
};

Eviivo.ToggleLink.prototype = {

    toggle: function(e, src, targetID) {
        if (this._isVisible(src)) {
            $get(targetID).style.display = 'none';
            src.innerHTML = this._text;
            src.mode = false;
        }
        else {
            $get(targetID).style.display = 'block';
            src.innerHTML = this._altText;
            src.mode = true;
        }

        // JIRA: EVMYWEB-3938
        // need to apply additional style to parent row
        $('#' + targetID).parents('tr').prev('.resupp_header').toggleClass('resupp_rowselected');

        // JIRA: EVMYWEB-756
        // it's necessary to fix map position after room prices are expanded or collapsed
        // use the map script control instance
        if (Eviivo && Eviivo.Controls && Eviivo.Controls.GoogleMap && Eviivo.Controls.GoogleMap.Instance) {
            Eviivo.Controls.GoogleMap.Instance.scrollMapAfterResize();
        }

    },

    _isVisible: function(e) {
        if (typeof (e.mode) == 'undefined') {
            e.mode = false;
        }

        return e.mode;
    }
};

Eviivo.ToggleLink.registerClass('Eviivo.ToggleLink', null);

Eviivo.ToggleLink.create = Eviivo$ToggleLink$create = function(text, altText) {
    Sys.Application.add_load(function() {
        Eviivo.ToggleLink.Instance = new Eviivo.ToggleLink(text, altText);
    });
};

//JIRA: EVMYWEB-2269 BookMark links
Type.registerNamespace('Eviivo.Bookmarks');

// Client script that constructs the bookmark anchor and child img Tag (based on culture)
Eviivo.Bookmarks = function(className, urlFieldId, cultureCode, linkSrc, imageSrc) {

    var e = Function._validateParams(arguments, [
        { name: "className", type: String },
        { name: "urlFieldId", type: String },
        { name: "cultureCode", type: String },
        { name: "linkSrc", type: String },
        { name: "imageSrc", type: String }
    ]);
    if (e) throw e;

    // private fields
    this._url = this.GetUrl(urlFieldId);
    this._links = [];
    this._imgs = [];

    var anchorTags = document.getElementsByTagName("A");
    for (var i = 0; i < anchorTags.length; i++) {
        var link = anchorTags[i];
        if (Sys.UI.DomElement.containsCssClass(link, className)) {

            link.href = linkSrc;
            link._url = this._url;
            // creating image (w.r.t Culture) instead of link text
            var linkImageChild = document.createElement("img");
            linkImageChild._srcUrl = imageSrc;
            linkImageChild.src = String.format(imageSrc, cultureCode);
            linkImageChild.id = "imgBookMark" + i;

            // TODO: fix EVMYWEB-2463 - unable to add event to the error event, due to Error.invalidOperation(Sys.Res.addHandlerCantBeUsedForError)
            // NOTE: this error happens only when using debug version of MicrosoftAjax script
            try {
                $addHandlers(window, { "error": this._onError }, linkImageChild);
            } catch (Error) { }

            link.appendChild(linkImageChild);

            $addHandlers(link, { "mouseover": this._onMouseOver }, link);
            $addHandlers(link, { "mouseout": this._onMouseOut });
            $addHandlers(link, { "click": this._onClick });
            this._imgs.push(linkImageChild);
            this._links.push(link);

            var element = document.getElementById("imgBookMark" + i);
            if ((element.complete != null) && (!element.complete)
                || (element.offsetHeight == 0)) {
                // image not loaded, therefore, place the Image of en culture (English)
                element.src = String.format(imageSrc, 'en');
            }

        }
    }
};

// Function invoked on setInterval. Removes the class added to Currency drop down and makes it visible.
// only when the AddThis button pop up is closed.
Eviivo.Bookmarks.ShowSelectTag = Eviivo$Bookmarks$ShowSelectTag = function() {
    //"at15s" and "at16p", are the DIV ID's of the AddThis button popup window.
    if (document.getElementById('at15s').style.display == 'none' && document.getElementById('at16p').style.display == 'none') {
        //removing the class added to the curency control to make it visible.
        var selectTags = document.getElementsByTagName("SELECT");
            for(var i=0;i<selectTags.length;i++) {
                Sys.UI.DomElement.removeCssClass(selectTags[i], 'hideContainer'); // "hideContainer" class hides the Tag.
            }
        clearInterval(Eviivo$Bookmarks$TimeInterval);
    }
};

Eviivo.Bookmarks.prototype = {

    _onMouseOver: function(e) {
        //For IE6, hiding all drop-down's, since SELECT tags are overlapping with the AddThis button pop-up
        if ((Sys.Browser.agent == Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
            var selectTags = document.getElementsByTagName("SELECT");
            for (var i = 0; i < selectTags.length; i++) {
                Sys.UI.DomElement.addCssClass(selectTags[i], 'hideContainer'); // "hideContainer" class hides the Tag.
            }
            Eviivo$Bookmarks$TimeInterval = setInterval("Eviivo$Bookmarks$ShowSelectTag()", 1000);
        }
        //[TITLE] taken as document.title
        return addthis_open(this, '', this._url, '[TITLE]');
    },
    _onMouseOut: function() {
        return addthis_close();
    },
    _onClick: function() {
        return addthis_sendto();
    },
    _onError: function(e) {
        //default to english when no image for the culture is available.
        this.src = String.format(this._srcUrl, 'en');
    },
    GetUrl: function(urlFieldId) {
        var element = $get(urlFieldId);
        if (element) {
            return element.value;
        }
    },
    Add: function(e) {
        var url = this.href;
        var title = document.title;
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && window.external) {
            window.external.AddFavorite(url, title);
        } else if (Sys.Browser.agent == Sys.Browser.Firefox && window.sidebar) {
            window.sidebar.addPanel(title, url, "");
        }
        e.preventDefault();
        e.stopPropagation();
        return false;
    },
    // Cleanup all attached handlers and element references
    dispose: function() {
        if (this._links) {
            for (var i = 0; i < this._links.length; i++) {
                $clearHandlers(this._links[i]);
            }
        }
        if (this._imgs) {
            for (var i = 0; i < this._imgs.length; i++) {
                $clearHandlers(this._imgs[i]);
            }
        }
        this._url = null;
        this._links = null;
        this._imgs = null;

        Eviivo.Bookmarks.callBaseMethod(this, 'dispose');
    }
};

Eviivo.Bookmarks.registerClass('Eviivo.Bookmarks', null, Sys.IDisposable);

// Create a singleton bookmarks script instance
Eviivo.Bookmarks.create = Eviivo$Bookmarks$create = function(className, urlFieldId, cultureCode, linkSrc, imageSrc) {
    Sys.Application.add_load(function() {
        Eviivo.Bookmarks.Instance = new Eviivo.Bookmarks(className, urlFieldId, cultureCode, linkSrc, imageSrc);
    });
};

//JIRA:EVMYWEB-3115 : location log tracking data
Eviivo.LogLocation = function(ctrl) {
    var resultsNumber = document.getElementById("resultsNumber");
    var urlMappingInfoReferrer = document.getElementById("urlMappingInfoReferrer");
    var number = resultsNumber ? parseInt(resultsNumber.innerHTML, 0) : 0;
    //JIRA: EVMYWEB-4159 : Javascript errors display when click on geoname with apostrophe on Refinesearch.aspx
    setTimeout('Eviivo.Distribution.Presentation.LocationServiceProxy.LogLocation(document.location.href, "' + ctrl.href + '", ' + number + ', "' + urlMappingInfoReferrer.innerHTML + '")', 0);
    setTimeout('document.location.href="' + ctrl.href + '"', 50);
    
    return false;
};

Eviivo.LogUserEvent = function(ctrl) {
    Eviivo.Distribution.Presentation.LocationServiceProxy.LogUserEvent('LinkClicked', ctrl.href);
};

//EVMYWEB-5001 Supplements - Phase 2 (WLS) (Rel 27)
(function(window) {
    eviivo.wls.supplements = eviivo.wls.supplements || {};
    eviivo$wls$supplements = eviivo.wls.supplements;
    // timeout interval in ms
    eviivo$wls$supplements.delay = 200;

    // initialise the supplements config
    eviivo$wls$supplements.init = function (crate, baseFormat) {
        eviivo.wls.supplements.baseFormat = baseFormat;

        eviivo$wls$supplements.calculatePrices();
        // NOTE: don't want to bind (live) events to various controls, due to various bugs in jQuery and change handlers in IE
        // instead will calculate all supplements' prices every 200ms
        eviivo$wls$supplements.timeout = setTimeout(eviivo$wls$supplements.calculatePrices, eviivo$wls$supplements.delay);
    };

    // calculate total prices for all supplements
    eviivo$wls$supplements.calculatePrices = function() {
        // find all supplement_room controls
        $('.supplement_room').each(function() {
            calculatePrice(this);
        });
        // recursive call
        eviivo$wls$supplements.timeout = setTimeout(eviivo$wls$supplements.calculatePrices, eviivo$wls$supplements.delay);
    };

    // calculates the supplement totals based on the supplement price, selected adults or children quantity and checked dates
    function calculatePrice(element) {
            var supplement = $(element);
            // get the supplement price
            var price = new Number(supplement.find('.supplement_price').html());
            var priceChild = new Number(supplement.find('.supplement_price_child').html());
            // find the total placeholder
            var totalElement = supplement.find('.room_price');

            // are there checkboxes to control the quantity?
            var noChecked = 1;
            if(supplement.find('.checkbox_nights_selection').length > 0) {
                noChecked = supplement.find('input[type=checkbox]:checked').length;
            }

            var quantity = 1;
            var quantityControl = supplement.find('.supplement_control');
            if(quantityControl.length > 0) {
                quantity = parseInt(quantityControl.val(),0);
            }
            var quantityChild = 1;
            var quantityChildControl = supplement.find('.supplement_control_child');
            if(quantityChildControl.length > 0) {
                if (quantityChildControl.is(':disabled') == true) {
                    // The child control is disabled for Multiple room - "All guests" supplements
                    // selecting a non-zero adult quantity should automatically set the child dropdown to its non-zero value. 
                    // Similarly, selecting 0 from the adult or child quantity should set the other dropdown to 0. 
                    if (quantity > 0) {
                        quantityChildControl.get(0).selectedIndex = 1;
                    } else {
                        quantityChildControl.get(0).selectedIndex = 0;
                    }
                }
                quantityChild = parseInt(quantityChildControl.val(),0);
            }

            var totalPrice = price * quantity * noChecked;
            var totalChildPrice = priceChild * quantityChild * noChecked;

            var selectedPrice = new Number(totalPrice.toFixed(2)) + new Number(totalChildPrice.toFixed(2));
            totalElement.html(String.localeFormat(eviivo$wls$supplements.baseFormat, selectedPrice));
    }

})(this);

// JIRA: EVMYWEB-1333 - Calendar View of Availability for serviced accommodation when there is no availability for the selected provider with the specific search criteria used
Type.registerNamespace('Eviivo.AvailabilityMessages');
Eviivo.AvailabilityMessages = function(containerId, triggersClassName, messagesElementId) {

    this._triggersClassName = triggersClassName;
    this._container = $get(containerId);
    this._messagesElement = $get(messagesElementId);
    this._triggers = [];
    if(this._container && this._messagesElement) 
    {
        // JIRA: EVMYWEB-1641
        // need to move messagesElement out of its containers, because they have relative position
        var messagesElement = this._messagesElement.parentNode.removeChild(this._messagesElement);
        document.body.appendChild(messagesElement);
    
        var divs = this._container.getElementsByTagName('div');
        for(var i=0;i<divs.length;i++) {
            if(divs[i].className == triggersClassName) {
                // make the triger the parent element (td)
                var trigger = divs[i].parentNode;
                this._triggers.push(trigger);
                $addHandlers(trigger, { "mouseover": this._onMouseOver }, this);
                $addHandlers(trigger, { "mouseout": this._onMouseOut }, this);
            }
        }
    }
};

Eviivo.AvailabilityMessages.prototype = {

    _onMouseOver: function(e) {
        var target = e.target;
        // if the target is not TD tag, then it's nested DIV; need to get parent TD
        if(target.tagName != "TD") {
            target = target.parentNode;
        }        
	    var bounds = Sys.UI.DomElement.getBounds(target);
        this._messagesElement.style.top = (bounds.y) + 'px';
        this._messagesElement.style.left = (bounds.x + bounds.width) + 'px';
        this._messagesElement.className = "";
    },
    
    _onMouseOut: function(e) {
        this._messagesElement.className = "hidden";
    },

    dispose:function() {
        //clear handlers
        for(var i=0;i<this._triggers.length;i++) {
            $clearHandlers(this._triggers[i]);  
        }

        this._className = null;
        this._container = null;
        this._messagesElement = null;
        this._triggers = null;
        
        //Eviivo.AvailabilityMessages.callBaseMethod(this, 'dispose');
    }
};

Eviivo.AvailabilityMessages.registerClass('Eviivo.AvailabilityMessages', null, Sys.IDisposable);

// Create a singleton supplement script instance
Eviivo.AvailabilityMessages.create = Eviivo$AvailabilityMessages$create = function(containerId, triggersClassName, messagesElementId) {
    Sys.Application.add_load(function() {
        Eviivo.AvailabilityMessages.Instance = new Eviivo.AvailabilityMessages(containerId, triggersClassName, messagesElementId);
    });
};

// JIRA: EVMYWEB-1642
// Limiting the text entered for "element" to "charLimit"
Eviivo.CheckCharLimit = function (element, charLimit){
    if (element.value.length > charLimit)
    {
        element.value = element.value.substring(0,charLimit);
    }
};

// JIRA: EVMYWEB-2039 
// method to set the currency drop down value when clicked on browser back button (Search Results page)
Eviivo.SetCurrency = function(elementID) {
    var element = $get(elementID);
    if (currentISOValue && element){
        for(var i=0;i<=element.length-1;i++)
        {
            var currencyValue = element.options[i].value;
            if(currencyValue == currentISOValue)
            {
                element.selectedIndex = i;
                break;
            }
        } 
    }
};

Eviivo.SetCurrency.registerClass('Eviivo.SetCurrency', null, Sys.IDisposable);

Eviivo.SetCurrency.create = Eviivo$SetCurrency$create = function(elementID){
    Sys.Application.add_load(function() {
        Eviivo.SetCurrency.Instance = new Eviivo.SetCurrency(elementID);
    });
};

// JIRA: EVMYWEB-2452 TSU: Recently viewed items (rel 16)
Eviivo.ShowRecentItemDivTag = function(groupNumber) {

    var divTag;
    for (var i = 1; i <= 3; i++) {
        divTag = document.getElementById('group' + i);
        if (divTag !== null) {
            // Show the div tag whihc matches with the group number
            if (i == groupNumber) {
                divTag.className = 'lastview_visible';
            }
            // Hide the remaining div's of the recent items.
            else {
                divTag.className = 'lastview_hidden';
            }
        }
    }
};


// JIRA: EVMYWEB-3464 Guest reviews display on overview tab
Eviivo.ShowGuestReview = function() {

    //jQuery code
    $('.review_readMore').click(function() {
        $(this).parents('.review_wideblock').toggleClass('review_expanded');
    });
    $('.review_collapse').click(function() {
        $(this).parents('.review_wideblock').toggleClass('review_expanded');
    });
};

Eviivo.ShowGuestReview.prototype =
{
    dispose: function() {
        
        //jQuery Code
        $('.review_readMore').unbind('click');
        $('.review_collapse').unbind('click');
    }
};

Eviivo.ShowGuestReview.registerClass('Eviivo.ShowGuestReview', null, Sys.IDisposable);

Eviivo.ShowGuestReview.create = Eviivo$ShowGuestReview$create = function() {
    Sys.Application.add_load(function() {
    Eviivo.ShowGuestReview.Instance = new Eviivo.ShowGuestReview();
    });
};

// JIRA: EVMYWEB-3464 Guest reviews display on overview tab
Eviivo.ShowCheckAvailability = function() {

    //jQuery code
    $('.search_checkAvailability').click(function() {
        $(this).parents('.searchbox_searchsection').toggleClass('search_expanded');
    });
    
    $('.search_again').click(function() {
        $(this).parents('.searchbox_searchsection').toggleClass('search_changedetails');
    });
};

Eviivo.ShowCheckAvailability.prototype =
{
    dispose: function() {
        //jQuery Code
    $('.search_checkAvailability').unbind('click');
    $('.search_again').unbind('click');
    $('.msg_head').unbind('click');
    $('.sub_msg_head').unbind('click');
    }
};

Eviivo.ShowCheckAvailability.registerClass('Eviivo.ShowCheckAvailability', null, Sys.IDisposable);

Eviivo.ShowCheckAvailability.create = Eviivo$ShowCheckAvailability$create = function() {
    Sys.Application.add_load(function() {
        Eviivo.ShowCheckAvailability.Instance = new Eviivo.ShowCheckAvailability();
    });
};

Eviivo.SelectCard = function(controlValue, classPrefix, controlId) {
    // return if the credit card payment option is disabled
    if ($('#radioPaymentCard:disabled').length > 0) {
        return;
    }

    if ($('#' + controlId).length > 0) {
        $('#' + controlId).val(controlValue);
        if (typeof (validate) == 'function') {
            validate($('#' + controlId)[0]);
        }
    }
    
    // force updating the layout for credit card type
    $('.page_maincolumn')[0].className = 'page_maincolumn ' + classPrefix + controlValue;
};

// JIRA: EVMYWEB-5001 supplements - booking page
Eviivo.ShowSupplementDetails = function () {

    //jQuery code
    $('.extra_readMore').click(function () {
        $(this).parents('.summary_msg_body').toggleClass('extra_expanded');
    });
    $('.extra_collapse').click(function () {
        $(this).parents('.summary_msg_body').toggleClass('extra_expanded');
    });
};

Eviivo.ShowSupplementDetails.prototype =
{
    dispose: function () {

        //jQuery Code
        $('.extra_readMore').unbind('click');
        $('.extra_collapse').unbind('click');
    }
};

Eviivo.ShowSupplementDetails.registerClass('Eviivo.ShowSupplementDetails', null, Sys.IDisposable);

Eviivo.ShowSupplementDetails.create = Eviivo$ShowSupplementDetails$create = function () {
    Sys.Application.add_load(function () {
        Eviivo.ShowSupplementDetails.Instance = new Eviivo.ShowSupplementDetails();
    });
};

/* this must be at the bottom*/
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();



