/// <reference path="jquery-1.3.2-vsdoc2.js"/>
var delay = function(func) { setTimeout(func, 0); };

$(function() {

    if (isTsuEnvironment === false) {
        // 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')
        && $('.overview_thumbs').length > 0) {
            // Overview page - non-TSU only:
            // 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
                $('#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();
                    }
                    var element = $('#box_payment_details_bg');
                    element.removeClass('payment_type_select');
                    element.addClass('payment_type_paypal');
                    element.removeClass('payment_type_cards');
                    // 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');
                    }

                });
                $('#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();
                    }
                    var element = $('#box_payment_details_bg');
                    element.removeClass('payment_type_select');
                    element.addClass('payment_type_cards');
                    element.removeClass('payment_type_paypal');
                    // display different popup message for different payment type
                    $('#panelPopup,#box_payment_logos_box').removeClass('payment_type_paypal');

                });

                // 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();
                        $('.box_payment_type img').css('cursor', 'default');
                    }
                }
            }
        }
    } // if(isTsuEnvironment === false)

});              // $(function() {

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;
};

// redirect after sort order change
Eviivo.ChangeSort = function(selectElementID) {
    // get select element
    var element = $get(selectElementID);
    if (element) {
        // sort order value
        var value = element.value;
        // actual query string
        var url = self.document.location.search;
        // remove sort parameter if present
        url = url.replace(/&sort=(\d+)/i, '');
        //JIRA : 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, '');
        // redirect with new query string that has new sort parameter
        self.document.location.search = url + "&sort=" + value;
    }
};

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);
    });
};

// JIRA: EVMYWEB-1651 - Add message saying "we are processing your payment please don't click back" after compelte booking button is pressed
Eviivo.Submit = function(modalPopupId, validationFunction) {
    // need to do the client validation first before displaying the popup,
    if (typeof (validationFunction) == "function" && validationFunction() == false) {
        return false;
    }
    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
};
IndustryType.registerEnum("IndustryType");

Type.registerNamespace('Eviivo.Search');

//JIRA: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')) {
            Eviivo.Search.IndustryType = IndustryType.TEA;
            Eviivo.Search.IndustrySubType = 0;
        } 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 {
            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;
            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);
};

Eviivo.FlipImage.prototype = {

    previousImage: function() {
        this.setMainImage(--this._currentImageIndex);
    },

    nextImage: function() {
        this.setMainImage(++this._currentImageIndex);
    },

    setMainImage: function(index, urlRoom) {
        if (index < 0) {
            index = this._imageList.length - 1;
        }
        else if (index >= this._imageList.length) {
            index = 0;
        }
        //EVMYWEB-3620
        var imageCurrent = $(this._imageList[index]);
        var imgData = $('#providerThumbData' + index);
        var imageDescription = imageCurrent.attr('title');
        var imageTitle = imgData.attr('alt');

        if (isTsuEnvironment) {
            this._imageMain.attr('src', imgData.attr('value'));
            this._imageMain.attr('title', imageDescription);
            this._imageMain.attr('alt', imageTitle);
        } else {
            // set image as background of the viewport div
            this._imageMain.css("backgroundImage", "url(" + imgData.attr('value') + ")");
        }

        this._header.html(imageTitle);

        this._imageList.removeClass('selected_thumb');

        imageCurrent.addClass('selected_thumb');

        if (imageDescription.length === 0) {
            this._description.html("&nbsp;");
        }
        else {
            this._description.html(imageDescription);
        }

        //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._imageList.length - 1 : index - 1);
            $('#nextIndexField').val((parseInt(index) + 1) % this._imageList.length);
        }
    },

    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.SecurityCode = function ()
{
    this._element = $get('security_code_help');
    this._elementHelp = $get('security_code_help_box');
    
    if(this._element) 
    {
        $addHandlers(this._element, 
        {
            "mouseover" : this._onMouseOver,
            "mouseout" : this._onMouseOut
        },
        this);
    }   
};

Eviivo.SecurityCode.prototype = 
{
    _onMouseOver: function(e) {
        this._elementHelp.style.visibility = 'visible';
    },
    
    _onMouseOut: function(e) {    
	    this._elementHelp.style.left = '0px';	
        this._elementHelp.style.visibility = 'hidden';
    },

    dispose: function() 
    {
        $clearHandlers(this._element);
        Eviivo.SecurityCode.callBaseMethod(this, 'dispose');
    }
};

Eviivo.SecurityCode.Create = function() {
    Sys.Application.add_load(function() {
        new Eviivo.SecurityCode();
    });
};

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

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;
    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);
};

Type.registerNamespace('Eviivo.Supplements');

// Client script that calculates subtotal and total price of selected supplements
Eviivo.Supplements = function Eviivo$Supplements(controls, crate, baseFormat, exchangeFormat, roomTotalID, bookingTotal, minimumPayment, isFullPayment) {

    /// <summary locid="M:J#Eviivo.Supplements" />
    /// <param name="controls" type="Object">Array of supplement configuration controls</param>
    /// <param name="crate" type="Number">Currency exchange rate</param>
    /// <param name="baseFormat" type="String">Number format of the base culture</param>
    /// <param name="exchangeFormat" type="String">Number format of the selected currency</param>
    /// <param name="roomTotalID" type="String">ID of the element to update the room totals</param>
    /// <param name="bookingTotal" type="Number">Total booking value</param>
    /// <param name="minimumPayment" type="Number">Minimum payment</param>
    /// <param name="isFullPayment" type="Boolean">set to true if the payment option is FULLPAYMENT</param>
    /// <returns type="Function"></returns>
    var e = Function._validateParams(arguments, [
        { name: "controls", type: Object },
        { name: "crate", type: Number },
        { name: "baseFormat", type: String },
        { name: "exchangeFormat", type: String },
        { name: "roomTotalID", type: String },
        { name: "bookingTotal", type: Number },
        { name: "minimumPayment", type: Number },
        { name: "isFullPayment", type: Boolean }
    ]);
    if (e) throw e;

    // private fields
    this._changeHandler = null;
    this._controls = null;
    this._crate = new Number(crate);
    this._baseFormat = baseFormat;
    this._exchangeFormat = exchangeFormat;
    this._roomTotalID = null;
    // JIRA: EVMYWEB-4158 - PayPal Implementation - Booking Summary Page
    this._bookingTotal = new Number(bookingTotal);
    this._minimumPayment = minimumPayment;
    this._isFullPayment = isFullPayment;
    this.init(controls, roomTotalID);
};
// Create a singleton supplement script instance
Eviivo.Supplements.Instance = null;

Eviivo.Supplements.prototype = {

    init: function Eviivo$Supplements$init(controls, roomTotalID) {

        this._controls = controls;
        this._roomTotalID = roomTotalID;
        if (controls.length) {

            this._changeHandler = Function.createDelegate(this, this.calculatePrice);

            for (var i = 0; i < this._controls.length; i++) {
                this.initCheckbox(this._controls[i]);
            }

            // calculate price for the first time (needed after client back navigation)
            this.calculatePrice();
        }
    },

    // Initialize checkbox controls:
    // - find checkbox element from checkboxID and attach click handler
    // - find subtotal element from subtotalID
    // - passing price (for 1 unit)
    // - (optional) find quantity element from quantityID and attach change handler
    initCheckbox: function Eviivo$Supplements$initCheckbox(control) {

        var e = Function._validateParams(control, [
            { name: "checkboxID", type: String },
            { name: "subtotalID", type: String },
            { name: "price", type: Number },
            { name: "quantityID", type: String, mayBeNull: true, optional: true }
        ]);
        if (e) throw e;

        control.checkboxElement = $get(control.checkboxID);
        control.subtotalElement = $get(control.subtotalID);

        // NOTE: if elements are not found no errors thrown
        if (control.checkboxElement && control.subtotalElement) {
            $addHandler(control.checkboxElement, 'click', this._changeHandler);
            if (control.quantityID) {
                control.quantityElement = $get(control.quantityID);
                if (control.quantityElement) {
                    $addHandler(control.quantityElement, 'change', this._changeHandler);
                }
            }
        }
    },

    // Calculate supplement price:
    // - calculate subtotal price for each supplement
    // - calculate total supplements price
    calculatePrice: function Eviivo$Supplements$calculatePrice() {
        var total = new Number(0);
        var subtotal = new Number(0);
        var roomtotal = new Number(0);
        var control = null;
        var index;
        var prevIndex = 0;
        var roomTotalElement = null;

        for (var i = 0; i < this._controls.length; i++) {
            control = this._controls[i];
            subtotal = this.calculateSinglePrice(control);
            control.subtotalElement.innerHTML = String.format(this._baseFormat, subtotal);
            if (this._roomTotalID != '') {
                // Get the index of the supplement id. The index of all the supplements for a room should be the same.
                index = control.subtotalElement.id.substring(control.subtotalElement.id.length - 1);
                if (prevIndex != index) {
                    // when the index changes (0 to 1), the total should be assigned to the prev index room (room_price_0) 
                    // and the current index is the new room supplements (room_price_1)
                    // (assuming the supplements for different rooms are added in the order (room index will be in the order: 0, 1, 2..)).
                    roomTotalElement = $get(String.format(this._roomTotalID, prevIndex));
                    if (roomTotalElement) {
                        roomTotalElement.innerHTML = String.format(this._baseFormat, roomtotal);
                    }
                    roomtotal = new Number(0);
                    prevIndex = index;
                }
                // calculate the total of all the supplements (supplement1_0, supplement2_0...) per room (room_price_0).
                roomtotal += (control.checkboxElement.checked === true) ? subtotal : new Number(0);
            }
            total += (control.checkboxElement.checked === true) ? subtotal : new Number(0);
        }
        // the last index room total to be assigned to the room_price_[prevIndex]
        if (this._roomTotalID != '') {
            roomTotalElement = $get(String.format(this._roomTotalID, prevIndex));
            if (roomTotalElement) {
                roomTotalElement.innerHTML = String.format(this._baseFormat, roomtotal);
            }
        }
        control = null;

        // JIRA: EVMYWEB-1090 - Round total to 2 decimal points
        // JIRA: EVMYWEB-4158 - PayPal Implementation - Booking Summary Page:
        // - all prices are calculated for the base currency
        // - only the exchange comment has the price in the target currency (the one selected by the customer)
        var bookingTotal = this._bookingTotal + total;
        // if minimum payment is different from booking total, then it's a deposit payment
        // EVMYWEB-4238: Any payment [CUSTOMDEPOIST, BOOKINGDEPOSIT], other than FULLPAYMENT is a deposit payment.
        var bookingPay = this._isFullPayment ? bookingTotal : this._minimumPayment;
        var bookingDue = this._isFullPayment ? new Number(0) : (bookingTotal - bookingPay);
        $('.booking_total').html(String.format(this._baseFormat, bookingTotal));
        $('.booking_pay').html(String.format(this._baseFormat, bookingPay));
        $('.booking_due').html(String.format(this._baseFormat, bookingDue));
        $('.booking_exchange').html(String.format(this._exchangeFormat, bookingTotal * this._crate));
        $('.booking_exchange_pay').html(String.format(this._exchangeFormat, bookingPay * this._crate));
    },

    // Calculate single supplements price:
    // - price (when optional quantityElement is null)
    // - price * quantity (otherwise)
    // NOTE: quantity element is a dropdown (SELECT) - no check for element tagName
    calculateSinglePrice: function Eviivo$Supplements$calculateSinglePrice(control) {
        var quantity = 1;
        // get quantity based on other control
        if (control.quantityElement) {
            quantity = parseInt(control.quantityElement.item(control.quantityElement.selectedIndex).value, 0);
        }
        return new Number((control.price * quantity).toFixed(2));
    },

    // Cleanup all attached handlers and element references
    dispose: function Eviivo$Supplements$dispose() {
        if (this._checkboxElements.length > 0) {
            var control = null;
            for (var i = 0; i < this._controls.length; i++) {
                control = this._controls[i];
                $removeHandler(control.checkboxElement, 'click', this._changeHandler);
                control.checkboxElement = null;
                control.subtotalElement = null;
                if (control.quantityElement) {
                    $removeHandler(control.quantityElement, 'change', this._changeHandler);
                    control.quantityElement = null;
                }
            }
        }
        this._checkboxHandler = null;
        this._controls = null;

        Eviivo.Supplements.callBaseMethod(this, 'dispose');
    }
};

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

// Create a singleton supplement script instance
Eviivo.Supplements.create = Eviivo$Supplements$create = function(controls, crate, baseFormat, exchangeFormat, roomTotalID, bookingTotal, minimumPayment, isFullPayment) {
    Sys.Application.add_load(function() {
    Eviivo.Supplements.Instance = new Eviivo.Supplements(controls, crate, baseFormat, exchangeFormat, roomTotalID, bookingTotal, minimumPayment, isFullPayment);
    });
};

// 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');
    }
};

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;
};

/* this must be at the bottom*/
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


