var broken = Class.create();

broken.page = 
{
    initialize : function()
    {
        /** add onclick events for accessibility **/
        //if($('mm-quickfinder')) broken.util.addEvent($('mm-quickfinder'), 'click', broken.page.initQuickfinder);

        /** Initialize Startpage **/
        if($('startPageSlideShow'))          
           broken.page.initStartpage();

        /** Initialize slideshow for hotelpages **/
        if($('hotelSlideShow'))
           broken.page.initHotelSlideShow();

        /** Initialize Loginfields **/
        if($('memberLogin'))
            broken.page.fixLogin();

        /** Initialize GoogleMaps **/
        if($('inTheAreaMapHolder'))
            broken.googleMaps.initialize();

         /** calculate totalt price in booking **/
         if($('roomOneWrapper'))
            broken.booking.onload()

         if($('collapsableTable'))
            broken.page.initStayFolderTable();
         
         if($('press'))
            broken.page.initStayFolderPress();
            
         if($('stay_history'))
            broken.page.initStayHistory();
            
         if($('sitemap'))
           broken.page.setListItemClasses();
        
    },
    
    fixLogin : function ()
    {
        var userLabel = $('memberLogin').getElementsByTagName('label')[0].firstChild;
        var userText = userLabel.nodeValue;
        var userField = $('memberLogin').getElementsByTagName('input')[0];
        var passLabel = $('memberLogin').getElementsByTagName('label')[1].firstChild;
        var passText = passLabel.nodeValue;
        var passField = $('memberLogin').getElementsByTagName('input')[1];
        passField.id="oldPassField"
        var newPassField = document.createElement("input")
        newPassField.setAttribute("value", passText)
        newPassField.setAttribute("type","text"); 
        newPassField.setAttribute("class","inputField");  
        newPassField.style.width = passField.offsetWidth;
        passField.parentNode.appendChild(newPassField)
        
        if(passField.value == "")
            passField.style.display="none";
        else
            newPassField.style.display="none";
            
        userLabel.nodeValue = ""
        passLabel.nodeValue = ""
        
        userField.setAttribute("value", userText)
        
        userField.onfocus = function() {
            if(this.value == userText) this.value = ""
        }
        userField.onblur = function() {
            if(this.value == "") this.value = userText
        }
        
        newPassField.onfocus = function() {
            this.parentNode.childNodes[0].style.display = ""
            this.parentNode.childNodes[0].focus()
            this.style.display = "none"
            
        }
        passField.onblur = function() {
            if(this.value=="") {
                this.parentNode.childNodes[1].style.display = ""
                this.style.display = "none"
            }
        }

      
    },
    
    initStartpage : function()
    {
        this.startPageSlideShow = new broken.slideShowEngine({
            url: '/Templates/Public/Data/GetImageList.aspx?lang=en&r='+(Math.round((Math.random()*5000000))),
            path: '/root/hotelimagescollecton/hotelimages/image[@IsStartPageImage=True]',
            targetWrapper: 'startPageSlideShow',
            run: true,
            useAll: true,
            toggleAction: broken.page.toggleStartPageText  
         });
        
        if($('bookBtnPusle'))
            setTimeout(function()
            {
                new Effect.Opacity('bookBtnPusle', 
                {
                    duration:1,
                    transition: Effect.Transitions.linear,
                    from: 1, 
                    to: 0,
                    afterFinish: function()
                    {
                        new Effect.Opacity('bookBtnPusle', 
                        {
                            duration: 1,
                            from: 0, 
                            transition: Effect.Transitions.linear,
                            to: 1,
                            afterFinish : function() { $('bookBtn').style.background = 'none'; }
                        });
                    }
                });
            }, 1500);
                
        if($('startPageLeftArrow'))
            this.initMoveSlider();
            
    },
    
    
    toggleStartPageText : function()
    {
        var id = broken.page.startPageSlideShow.imageArray[broken.page.startPageSlideShow.currentPosition].hotelId;
        var textColor = broken.page.startPageSlideShow.imageArray[broken.page.startPageSlideShow.currentPosition].textcolor;
        var pagelinkurl = broken.page.startPageSlideShow.imageArray[broken.page.startPageSlideShow.currentPosition].pagelinkurl;
        
        $('featureHotelHolder').observe('click', function(){ broken.util.gotoPage(pagelinkurl) });
        
        var lastText = broken.page.startPageSlideShow._last.id == $(broken.page.startPageSlideShow.slideShowHolder0).id ? $('startPageSlideShowText') : $('startPageSlideShowText1');
        var nextText = broken.page.startPageSlideShow._last.id == $(broken.page.startPageSlideShow.slideShowHolder0).id ? $('startPageSlideShowText1') : $('startPageSlideShowText');
        
        var textImage = textColor == 'white' ?  '/images/startpage/startpage.text.white.png' : '/images/startpage/startpage.text.black.png';
        
        $(nextText.id).getElementsByTagName('IMG')[0].src = textImage;
        
        var oldImageWidth = parseInt($('featureHotelHolder').getElementsByTagName('IMG')[0].width);
        $('featureHotelHolder').style.width = oldImageWidth+'px';
        
        if(Prototype.Browser.IE){
            var imgTag = document.createElement('IMG');
            $('featureHotelHolder').replaceChild(imgTag, $('featureHotelHolder').getElementsByTagName('IMG')[0]);
            $('featureHotelHolder').getElementsByTagName('IMG')[0].src = '/images/hotels/feature_'+id+'.png';   
            var pic = new Image();
            pic.src = '/images/hotels/feature_'+id+'.png';
            if(pic.complete) broken.page.changeFeatureHotel()
            else pic.onload = broken.page.changeFeatureHotel;                 
        }else{
            $('featureHotelHolder').getElementsByTagName('IMG')[0].src = '/images/hotels/feature_'+id+'.png';
            $('featureHotelHolder').getElementsByTagName('IMG')[0].observe('load', broken.page.changeFeatureHotel);
        }
        
        new Effect.Appear($(nextText.id), {
            duration: 2.0, 
            afterFinish : function(){
                if (Prototype.Browser.IE){
                    $(nextText.id).style.setAttribute('filter', 'alpha(opacity=100)');
                    $(lastText.id).style.setAttribute('filter', 'alpha(opacity=0)');
                }else{                    
                    $(lastText.id).style.opacity = '0';
                    $(nextText.id).style.opacity = '100';
                }    
                $(lastText.id).style.zIndex = (broken.page.startPageSlideShow._z)+1;
            }
        });
        

    },
    
    changeFeatureHotel : function()
    {
        var imageWidth = parseInt($('featureHotelHolder').getElementsByTagName('IMG')[0].width);
        new Effect.Morph('featureHotelHolder', {
            duration: 1.0,
            style: {
                width: imageWidth+'px'
            }
        }) 
        
        if (!Prototype.Browser.IE)
            $('featureHotelHolder').getElementsByTagName('IMG')[0].stopObserving('load');
    },
    
    initHotelSlideShow : function()
    {
        var run = $('IsOnHotelStartPage').value == 'True' ? true : false;
        
        this.hotelSlideShow = new broken.slideShowEngine({
            url: '/Templates/Public/Data/GetImageList.aspx?lang=en&r='+(Math.round((Math.random()*5000000))),
            path: '/root/hotelimagescollecton/hotelimages/image[@IsStartPageImage=False]',
            targetWrapper: 'hotelSlideShow',
            toggleAction: broken.page.changeHotelText,
            run: run,
            useAll: false
         });       
    },
    
    changeHotelSlide : function(direction)
    {
        
        var timeOutId = this.hotelSlideShow.timeout;
        
        clearTimeout(timeOutId);
        this.hotelSlideShow.togglePictures('human', direction);
    },
    
    changeHotelText : function(direction)
    {
        if(this.pagelinkurl == '')
            $('pictureLabel').innerHTML = this.imagedescription;
        else
            $('pictureLabel').replaceChild(Builder.node('a',{ style: 'display:inline', href: this.pagelinkurl }, this.imagedescription), $('pictureLabel').firstChild)
    },
    
    initQuickfinder : function(e, lang)
    {  
        
        if(!e) var e = window.event;
        
        try{
            e.preventDefault();
        }
            catch(err)
        {
            e.cancelBubble = true;
    	    e.returnValue = false;
        }
        
        
        if($('quickfinderWrapper')){
            
        
            broken.page.changeQuickfinderBtn();
            
            var topPx = $('mm-quickfinderClose') ? 0 : -(parseInt($('quickfinderContainer').getHeight()));
            
            new Effect.Morph('quickfinderContainer',{
                duration: 1.0,
                style:{
                    top: parseInt(topPx) -46 + 'px'
                },
                beforeStart: function(){ 
                    $('quickfinderWrapper').setStyle({ display: 'block' });
                },
                afterFinish: function(){ 
                    if(parseInt($('quickfinderContainer').getStyle('top').replace('px', '')) < -46)
                        $('quickfinderWrapper').setStyle({ display: 'none' });
                    else
                        $('quickfinderWrapper').setStyle({ display: 'block' });
                }
            
            
            });
            
            
        }else{
            var r = Math.round((Math.random()*5000000));
            broken.ajax.doAjax('/Templates/Public/Data/GetHotelList.aspx?lang='+lang+'&r='+r, broken.page.createQuickfinder);
        }
    },
    
    createQuickfinder : function(x)
    {
        var hotels = broken.xpath.selectNodes(x, '/root/hotels', true);
        var host = 'http://'+window.location.host;
        var swedenHotels = broken.xpath.selectNodes(hotels, '/country[@code=SE]/hotel', true);
        var norwayHotels = broken.xpath.selectNodes(hotels, '/country[@code=NO]/hotel', true);
        var denmarkHotels = broken.xpath.selectNodes(hotels, '/country[@code=DK]/hotel', true);
        var names = broken.xpath.selectNodes(hotels, '/country[@name]', false);
        
        var quickfinder = Builder.node('DIV', { id : 'quickfinderWrapper' });
        var container = Builder.node('DIV', { id : 'quickfinderContainer', className : 'clearfix' });
        var swedenList = Builder.node('UL', { id : 'swedenList' });
        var swedenList2 = Builder.node('UL', { id : 'swedenList2' });
        var norwayList = Builder.node('UL', { id : 'norwayList' });
        var denmarkList = Builder.node('UL', { id : 'denmarkList' });
        var swedenH3 = Builder.node('H3', { id : 'swedenH3', className: 'floatLeft' }, names[0].toString().toUpperCase());
        var norwayH3 = Builder.node('H3', { id : 'norwayH3' }, names[1].toString().toUpperCase());
        var denmarkH3 = Builder.node('H3', { id : 'denmarkH3' }, names[2].toString().toUpperCase());
        
        $('framework').appendChild(quickfinder);
        $('quickfinderWrapper').appendChild(container);
        $('quickfinderContainer').appendChild(swedenH3);
        $('quickfinderContainer').appendChild(norwayH3);
        $('quickfinderContainer').appendChild(swedenList);
        $('quickfinderContainer').appendChild(swedenList2);
        $('quickfinderContainer').appendChild(norwayList);
        $('quickfinderContainer').appendChild(denmarkH3);
        $('quickfinderContainer').appendChild(denmarkList);
        
        var l = 0;
        var uls = ['swedenList','swedenList2', 'norwayList', 'denmarkList'];
        
        for(var i = 0; i < swedenHotels.length; i++)
        {
            if(swedenHotels.length > i)
            {
                var item = swedenHotels[i];
                var nv = broken.xpath.findNodes(item, 'name', false, false);
                var link = broken.xpath.findNodes(item, 'link', false, false);
                var city = Prototype.Browser.IE ? item.attributes.getNamedItem("city").nodeValue : item.attributes.city.nodeValue;
                
                var li = Builder.node('li', [
                    Builder.node('a', { href : host+link[0] }, [
                        Builder.node('strong', city.toString().toUpperCase()),
                        Builder.node('span', '//'),
                        Builder.node('span', nv[0].toString().toUpperCase())
                    ])
                ]);
                
                if(i > ((swedenHotels.length-1)/2))
                    $(uls[1]).appendChild(li);
                else
                    $(uls[0]).appendChild(li);
            }
        };
        
        for(var i = 0; i < norwayHotels.length; i++)
        {
            if(norwayHotels.length > i)
            {
                var item = norwayHotels[i];
                var nv = broken.xpath.findNodes(item, 'name', false, false);
                var link = broken.xpath.findNodes(item, 'link', false, false);
                var city = Prototype.Browser.IE ? item.attributes.getNamedItem("city").nodeValue : item.attributes.city.nodeValue;
                
                var li = Builder.node('li', [
                    Builder.node('a', { href : host+link[0] }, [
                        Builder.node('strong', city.toString().toUpperCase()),
                        Builder.node('span', '//'),
                        Builder.node('span', nv[0].toString().toUpperCase())
                    ])
                ]);
                $(uls[2]).appendChild(li);
            }
        };
        
        for(var i = 0; i < denmarkHotels.length; i++)
        {
            if(denmarkHotels.length > i)
            {
                var item = denmarkHotels[i];
                var nv = broken.xpath.findNodes(item, 'name', false, false);
                var link = broken.xpath.findNodes(item, 'link', false, false);
                var city = Prototype.Browser.IE ? item.attributes.getNamedItem("city").nodeValue : item.attributes.city.nodeValue;                
               
                var li = Builder.node('li', [
                    Builder.node('a', { href : host+link[0] }, [
                        Builder.node('strong', city.toString().toUpperCase()),
                        Builder.node('span', '//'),
                        Builder.node('span', nv[0].toString().toUpperCase())
                    ])
                ]);
                $(uls[3]).appendChild(li);
            }
        };
        
        broken.page.changeQuickfinderBtn();
        new Effect.Morph('quickfinderContainer',{
            duration: 1.0,
            style:{
                top: '0px'
            }
        });
    },
    
    changeQuickfinderBtn : function()
    {
        if($('mm-quickfinder'))
            $('mm-quickfinder').id = 'mm-quickfinderClose'; 
        else if($('mm-quickfinderClose'))
            $('mm-quickfinderClose').id = 'mm-quickfinder';
            
    }, 
    
    mapToggleMarker : function(sender, action)
    {
        var kind = sender.id.split('_')[0];
        var id = sender.id.split('_')[1];
        var link = kind == 'dotLink' ? 'mapLink_'+id : 'dotLink_'+id;
        
        if($(link)){
            if(action == 'active')
                $(link).addClassName('hover');
            else if(action == 'inactive')
                $(link).removeClassName('hover');
        }
    },
    
    quicksearch : function(sender)
    {
        if(sender.value.length > 1)
            broken.ajax.doAjax('/Templates/Public/Data/GetSearchResult.aspx?lang=en&searchQuery='+sender.value+'&r='+(Math.round((Math.random()*5000000))), null);
            
    },
    
    interval : 10000,
    initMoveSlider : function()
    {
        /** Collect pushes **/ 
        this.pushesCollection = new Array();
                
        $$('#framework .startPageOffer').each(
            function(item){
                broken.page.pushesCollection.push(item);
                item.style.position = 'absolute';  
                item.style.left = '9000px';       
            }
        );
        
        if(this.pushesCollection.length == 2)
        {
            for(var i = 0; i < 3; i++)
            {
                var node = this.pushesCollection[i].cloneNode(true);
                $('startPageOffersSlider').appendChild(node);
                this.pushesCollection.push(node);
            }   
        }
        
        /** Íf  only 2 puches, no arrows willl be shown **/
        if(this.pushesCollection.length <= 1){
            $('startPageLeftArrow').style.display = 'none';
            $('startPageRightArrow').style.display = 'none';
        }
        this.currentPush = 0;
        
        this.pushesCollection[0].style.left = '0px';
        this.pushesCollection[1].style.left = '920px';
        
        this.calculatePushesPositions(this.currentPush);
        
        
        var _this = this;
        
		setTimeout(function() 
		{ 
			_this.firstSlide(); 
		},this.interval * 3);
        
    },
    
    firstSlide : function() {
    	this.moveSlider('right', 'startPageOffersSlider', false);
		this.keepSliding();
    },
    
    keepSliding : function() {
    
        var _this = this;
		this.sliderInterval = setInterval(function()
        {
			_this.moveSlider('right', 'startPageOffersSlider', false);
        }, this.interval );
    },
    
    calculatePushesPositions : function(currentPosition)
    {
        if(currentPosition == 0)
            var leftPush = this.pushesCollection[(this.pushesCollection.length - 1)];
        else
            var leftPush = this.pushesCollection[(currentPosition - 1)];
        
        if(currentPosition == (this.pushesCollection.length - 1))
            var rightPush = this.pushesCollection[0];
        else
            var rightPush = this.pushesCollection[(currentPosition + 1)];
        
        if(this.pushesCollection[currentPosition].style.left == '')
            this.pushesCollection[currentPosition].style.left = '0px';
               
        /** Set styles for the pushes not visible **/     
        leftPush.style.left = (parseInt(this.pushesCollection[currentPosition].style.left) - 920) + 'px';
        rightPush.style.left = (parseInt(this.pushesCollection[currentPosition].style.left) + 920) + 'px';
    },
    
    moveSlider : function(sender, target, clear)
    {
        /** Failsafe **/
        if(typeof this.failSafe == 'undefined' || !this.failSafe)
        {
            if(clear)
                clearInterval(this.sliderInterval);
        
            /** Set Failsafe **/
            this.failSafe = true;
                       
            /** Getting the current position of the target **/
            var currentPosition = $(target).style.left;
            
            /** If currentPosition is not set, set it to 0 **/
            if(currentPosition == '')
                var currentPosition = 0;
                
            /** Let's set what way the slider should move **/
            var moveTo = sender == 'right' ? parseInt(currentPosition) - 920 : parseInt(currentPosition) + 920;
            
            /** currentPush is the first (to right) **/
            
            if(sender == 'right')
                this.currentPush = (this.currentPush++) >= (this.pushesCollection.length - 1) ? 0 : this.currentPush++;
            else
                this.currentPush = (this.currentPush--) <= 0 ? (this.pushesCollection.length-1) : this.currentPush--;
            
           
            
            /** Run Effect **/
            new Effect.Morph($(target),{
                duration: 0.5,
                style:{
                    left: moveTo+'px'
                }, 
                afterFinish: function()
                {
                    broken.page.failSafe = false
                    broken.page.calculatePushesPositions(broken.page.currentPush)
                }
            });
        }
    },
    
    toggleLanguageMenu : function()
    {
        /** Set display block to languageMenu **/
        var h = $('languageMenu').clientHeight == $('languageMenuWrapper').clientHeight ? 0 : $('languageMenu').clientHeight;
        new Effect.Morph('languageMenuWrapper', 
        {
            duration: 0.5,
            style:{
                height: h+'px'
            }
        });
    },
    
    doSearch : function(e, url)
    {
        if(!e) var e = window.event;
        
        try{
            e.preventDefault();
        }
            catch(err)
        {
            e.cancelBubble = true;
    	    e.returnValue = false;
        }
        
        var searchString = $('searchQuery').value;
        //debugger;
        window.location.href = url + '?searchQuery=' + searchString;
    },
    
    trySearch : function(e, url)
    {
        if(!e) var e = window.event;
        if(e && e.keyCode == 13)
            this.doSearch(e, url);
    },
    
    initStayFolderTable : function()
    {
        var links = $('collapsableTable').getElementsByClassName('collapsable_link');
        
        for(var i = 0; i < links.length; i++){
            $(links[i].getElementsByTagName('TD')[0]).getElementsByClassName('collapsable')[0].toggle();
            links[i].observe('click', function() { 
                this.getElementsByClassName('collapsable')[0].toggle();
                $(this.getElementsByTagName('TD')[1]).toggleClassName('down')
            });
       }
    },
    
    initStayFolderPress : function()
    {
        var links = $('press').getElementsByClassName('collapsable_link');
        
        for(var i = 0; i < links.length; i++){
            $(links[i].parentNode.parentNode).getElementsByClassName('collapsable')[0].toggle();
            links[i].observe('click', function() { 
                this.parentNode.parentNode.getElementsByClassName('collapsable')[0].toggle();
                this.toggleClassName('foldedout');
            });
       }
    }, 
    
    initStayHistory : function()
    {
        var links = $('stay_history').getElementsByClassName('collapsable_link');
        
        for(var i = 0; i < links.length; i++){
            $(links[i]).getElementsByClassName('collapsable')[0].toggle();
            links[i].observe('click', function() { 
                this.getElementsByClassName('collapsable')[0].toggle();
                this.toggleClassName('down');
            });
       }
    },
	
	setListItemClasses : function(){
        $$('ul.sitemaplist').each(function(menu) {
            $($(menu.immediateDescendants()).last()).addClassName('last-child');
        });
    }
}
broken.booking = {
	roomObject: function(name, price, persons, children, guaranteemethod) {
		this.Name = name;
		this.Price = price;
		this.Persons = persons;
		this.Children = children;
		this.GuaranteeMethod = guaranteemethod;
	},
	setRoom: function(sender, number, container, roomName, price, persons, children, guaranteemethod, dailyPrice, isBestDeal) {
		this.clearSelections(sender, container);
		var n = number == 1 ? 'One' : 'Two';
		var n = number == 3 ? 'Three' : n;

		this.roomSelected = new this.roomObject(roomName, price, persons, children, guaranteemethod);
		$('ctl00_MainContentRegion_room' + n + 'InfoPriceDataDt').className = "displayBlock";
		$('ctl00_MainContentRegion_room' + n + 'InfoPriceDataDd').className = "displayBlock";
		$('Room' + n + 'Info').innerHTML = this.roomSelected.Name;

		$('Room' + n + 'Price').innerHTML = this.roomSelected.Price;
		$('Room' + n + 'DailyPrice').innerHTML = dailyPrice;
		$('Room' + n + 'IsBestDeal').innerHTML = isBestDeal;

		$('r' + n + 'g').value = guaranteemethod;
		this.setGuarantee(this.roomSelected, 'GX');
		this.setRoomPrices(dailyPrice, isBestDeal);
	},
	setGuarantee: function(r, g) {
		var requiredGuarantee = false;
		var lateArrival = false;
		var isBestDeal = false;
		var timeSelect = $('ctl00_MainContentRegion_EstimatedArrivalTime');
		if (timeSelect != null) {
			if (parseInt(timeSelect.value) >= 16)
				lateArrival = true;
		}
	
		if (parseInt($('RoomOneIsBestDeal').innerHTML) == 1 || parseInt($('RoomTwoIsBestDeal').innerHTML) == 1 || parseInt($('RoomThreeIsBestDeal').innerHTML) == 1) {
			isBestDeal = true;

		}

		if (isBestDeal|| lateArrival) {
			$('completeBookingButton').style.display = 'none';
			//$('CardInfo').style.display = 'block';
			if ($("payOnline") != null) {
				$('cardInfos').style.display = 'none';
//				if (lateArrival && isBestDeal) {
//					$('CreditCardReasonPayOnline').innerHTML = $('flexplusbestdeal').value;
//				}
				if (isBestDeal) {
					$('CreditCardReasonPayOnline').innerHTML = $('requiredGuarantee').value;
				}
				else {
					$('CreditCardReasonPayOnline').innerHTML = $('lateArrival').value;
				}
			}
			else {
				$('cardInfos').style.display = 'block';
				if ($("onlinePayment") != null) {

//					if (lateArrival && isBestDeal) {
//						$('CreditCardReasonOnlinePayment').innerHTML = $('flexplusbestdeal').value;
//					}
					if (isBestDeal) {
						$('CreditCardReasonOnlinePayment').innerHTML = $('requiredGuarantee').value;
					}
					else {
						$('CreditCardReasonOnlinePayment').innerHTML =  $('lateArrival').value;
					}
				}
			}
			$('Guarantee').style.display = 'inline';
			$('NoGuaranteeIntro').style.display = 'none';
			$('NoGuaranteeText').style.display = 'none';
		}
		else {
			$('completeBookingButton').style.display = 'block';
			//$('CardInfo').style.display = 'none';
			$('cardInfos').style.display = 'none';
			$('Guarantee').style.display = 'none';
			$('NoGuaranteeIntro').style.display = 'inline';
			$('NoGuaranteeText').style.display = 'inline';
		}
	},


	changeArrivalTime: function() {
		if (this.roomSelected) {

			var requiredGuarantee = false;
			var lateArrival = false;
			var timeSelect = $('ctl00_MainContentRegion_EstimatedArrivalTime');
			if (timeSelect != null) {
				if (parseInt(timeSelect.value) >= 16)
					lateArrival = true;
			}

			if (parseInt($('RoomOneIsBestDeal').innerHTML) == 1 || parseInt($('RoomTwoIsBestDeal').innerHTML) == 1 || parseInt($('RoomThreeIsBestDeal').innerHTML) == 1) {
				requiredGuarantee = true;
			}
			

			if (requiredGuarantee || lateArrival) {
				$('completeBookingButton').style.display = 'none';
				//$('CardInfo').style.display = 'block';
				if ($("payOnline") != null) {
					$('cardInfos').style.display = 'none';
					if (requiredGuarantee) {
						$('CreditCardReasonPayOnline').innerHTML = $('requiredGuarantee').value;
					}
					else {
						$('CreditCardReasonPayOnline').innerHTML = $('lateArrival').value;
					}
				}
				else {
					$('cardInfos').style.display = 'block';

					if ($("onlinePayment") != null) {
						if (requiredGuarantee) {
							$('CreditCardReasonOnlinePayment').innerHTML = $('requiredGuarantee').value;
						}
						else {
							$('CreditCardReasonOnlinePayment').innerHTML = $('lateArrival').value;
						}
					}
				}
				$('Guarantee').style.display = 'inline';
				$('NoGuaranteeIntro').style.display = 'none';
				$('NoGuaranteeText').style.display = 'none';

			}
			else {
				$('completeBookingButton').style.display = 'block';
				//$('CardInfo').style.display = 'none';
				$('cardInfos').style.display = 'none';
				$('Guarantee').style.display = 'none';
				$('NoGuaranteeIntro').style.display = 'inline';
				$('NoGuaranteeText').style.display = 'inline';
			}

			this.setRoomPrices();
		}
	},
	setRoomPrices: function(dailyPrice, isBestDeal) {

		var roomSum = 0, specialPriceSum = 0, specialDailyPriceSum = 0;
		var lateArrival = false;
		var timeSelect = $('ctl00_MainContentRegion_EstimatedArrivalTime');

		if (timeSelect != null) {
			if (parseInt(timeSelect.value) >= 16) {
				lateArrival = true;
			}
		}


		if (parseInt($('RoomOneIsBestDeal').innerHTML) == 0 && lateArrival)
			specialPriceSum = (parseInt(specialPriceSum) + parseInt($('RoomOneDailyPrice').innerHTML));
		else if ((parseInt($('RoomOneIsBestDeal').innerHTML) == 1))
			specialPriceSum = (parseInt(specialPriceSum) + parseInt($('RoomOnePrice').innerHTML));


		if (parseInt($('RoomTwoIsBestDeal').innerHTML) == 0 && lateArrival)
			specialPriceSum = (parseInt(specialPriceSum) + parseInt($('RoomTwoDailyPrice').innerHTML));
		else if ((parseInt($('RoomTwoIsBestDeal').innerHTML) == 1))
			specialPriceSum = (parseInt(specialPriceSum) + parseInt($('RoomTwoPrice').innerHTML));

		if (parseInt($('RoomThreeIsBestDeal').innerHTML) == 0 && lateArrival)
			specialPriceSum = (parseInt(specialPriceSum) + parseInt($('RoomThreeDailyPrice').innerHTML));
		else if ((parseInt($('RoomThreeIsBestDeal').innerHTML) == 1))
			specialPriceSum = (parseInt(specialPriceSum) + parseInt($('RoomThreePrice').innerHTML));


		if ($('RoomOnePrice').innerHTML != 0) {
			roomSum = (parseInt(roomSum) + parseInt($('RoomOnePrice').innerHTML));
		}

		if ($('RoomTwoPrice').innerHTML != 0) {
			roomSum = (parseInt(roomSum) + parseInt($('RoomTwoPrice').innerHTML));
		}

		if ($('RoomThreePrice').innerHTML != 0) {
			roomSum = (parseInt(roomSum) + parseInt($('RoomThreePrice').innerHTML));
		}

		if (roomSum > 0) {
			$('ctl00_MainContentRegion_totalRoomPricesDt').className = "displayBlock totalPrice";
			$('ctl00_MainContentRegion_totalRoomPricesDd').className = "displayBlock totalPrice";
			$('TotalRoomPricesInfo').innerHTML = roomSum;
		}


		if ($("onlinePayment") != null) {
			$('TotalRoomPricesInfoCreditCardOnlinePayment').innerHTML = parseInt(specialPriceSum);
		}
		if ($("payOnline") != null) {
			$('TotalRoomPricesInfoCreditCardPayOnline').innerHTML = parseInt(specialPriceSum);
		}
	},
	clearSelections: function(sender, container) {
		var inputs = $(container).getElementsByTagName('INPUT');
		for (var i = 0; i < inputs.length; i++) {
			var item = inputs[i];
			if (item.type == 'radio' || item.getAttribute('type') == 'radio') {
				item.checked = false;
				$(item.parentNode.parentNode).removeClassName('marked');
			}
		};
		sender.checked = true;
		sender.parentNode.parentNode.addClassName('marked');
	},
	loadRooms: function(startText, stoppText) {
		if (window.scrollY) {    // Firefox
			var _y = window.scrollY;
		} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
			var _y = document.documentElement.scrollTop;
		}
		if (typeof document.body.style.maxHeight == "undefined") {
			var selects = $('framework').getElementsByTagName('select');
			for (var i = 0; i < selects.length; i++)
				selects[i].style.display = 'none';
		}
		var loaderBoxBackground = Builder.node('DIV', { className: 'roomLoaderBackground' });
		var loaderBox = Builder.node('DIV', { className: 'roomLoaderBox', id: 'roomLoader' }, [Builder.node('H1', startText), Builder.node('img', { src: '/images/animering.gif', alt: 'Loading...' }), Builder.node('P', stoppText)]);
		loaderBoxBackground.style.height = $('framework').clientHeight + 'px';
		loaderBox.style.top = (_y + 200) + "px";
		loaderBox.style.left = ((document.body.clientWidth / 2) - 125) + "px";
		document.body.appendChild(loaderBox);
		document.body.appendChild(loaderBoxBackground);
		//new Effect.Opacity('roomLoader', { duration: 1.0, from: 0, to: 0.99 });
	},
	toggleRoomInfo: function(sender) {
		var div = sender.parentNode.parentNode.parentNode;
		if (div.className == 'normal')
			div.className = 'expanded';
		else
			div.className = 'normal';
	},

	openRoomInfo: function(sender) {
		var div = sender.parentNode.parentNode.parentNode;
		if (div.className == 'normal') {
			div.className = 'expanded';
		}
	},
	//Need to get the information on what kind of room that is booked Best Deal or Flex
	//
	onload: function() {
		var rooms = ['roomOneWrapper', 'roomTwoWrapper', 'roomThreeWrapper']
		for (var i = 0; i < rooms.length; i++) {
			if ($(rooms[i])) {
				var cb = $(rooms[i]).getElementsByTagName('INPUT');
				if (cb.length > 0) {
					for (var j = 0; j < cb.length; j++) {
						if (cb[j].checked) {
							var s = cb[j].attributes.onclick.value.split(',');
							broken.booking.setRoom(cb[j], parseInt(s[1]), s[2].split('"')[1], s[3].split('"')[1], s[4].split('"')[1], s[5].split('"')[1], s[6].split('"')[1], s[7].split(')')[0].split('"')[1], s[8].split(')')[0].split('"')[1], s[9].split(')')[0].split('"')[1]);
						}
					}
				}
			}
		}
	}

}
broken.ajax ={
    doAjax: function(url, callback) {
        /** need error handling **/
        new Ajax.Request(url, {
            onSuccess: function(transport) {
                callback(transport.responseXML);
            }
        });
    }
}
broken.googleMaps ={
    initialize: function() {
        if (GBrowserIsCompatible() && $('inTheAreaMapHolder')) {
            map = new GMap2($('inTheAreaMapHolder'));
            map.setCenter(new GLatLng(37.4419, -122.1419), 13);
            map.addControl(new GLargeMapControl());
            gdir = new GDirections(map, $('directions'));
            GEvent.addListener(gdir, "error", broken.googleMaps.handleErrors);
            GEvent.addListener(gdir, "load", function() {
                G_START_ICON.shadow = '';
                G_START_ICON.iconSize = new GSize(21, 21);
                G_START_ICON.iconAnchor = new GPoint(10, 21);
                G_START_ICON.image = $('directionsFrom').checked ? '/images/clear.gif' : '/images/map.arrow.small.gif';
                G_END_ICON.shadow = '';
                G_END_ICON.iconSize = new GSize(21, 21);
                G_END_ICON.iconAnchor = new GPoint(10, 21);
                G_END_ICON.image = $('directionsTo').checked ? '/images/clear.gif' : '/images/map.arrow.small.red.gif';
            });
            GEvent.addListener(gdir, "addoverlay", function() {
                var icons = $('directions').getElementsByTagName('IMG');
                icons[0].src = '/images/map.arrow.small.gif';
                icons[0].style.margin = '5px';
                icons[1].src = '/images/map.arrow.small.red.gif';
                icons[1].style.margin = '5px';
            });
            mgr = new GMarkerManager(map);
            markers = new Array();
            this.getInTheAreaMarkers();
        }
    },
    tryGetDirections: function(e, locale) {
        if (!e) var e = window.event;
        if (e && e.keyCode == 13)
            this.getDirections(locale)
    },
    getDirections: function(e, locale) {
        if (!e) var e = window.event;
        try {
            e.preventDefault();
        }
        catch (err) {
            e.cancelBubble = true;
            e.returnValue = false;
        }
        $('errorDirections').innerHTML = '';
        $('directions').innerHTML = '';
        var vcard = document.getElementsByClassName('vcard')[0];
        var city = vcard.getElementsByClassName('locality')[0].innerHTML;
        var country = vcard.getElementsByClassName('country-name')[0].innerHTML;
        var latLng = new GLatLng($('googleMapsCoords').value.split(',')[0], $('googleMapsCoords').value.split(',')[1])
        var latLngString = latLng.lat() + ',' + latLng.lng();
        if (!$('directionsFrom').checked && !$('directionsTo').checked) {
            this.handleErrors('You didn\'t check what direction you want to go');
            return;
        }
        if ($('toFromInput').value.length == 0) {
            this.handleErrors('You must enter an address.');
            return;
        }
        if ($('directionsFrom').checked)
            var fromAddress = '@' + latLngString;
        else
            var fromAddress = $('toFromInput').value + ' ' + $('toFromInputCity').value + ' ' + country;
        if ($('directionsTo').checked)
            var toAddress = '@' + latLngString;
        else
            var toAddress = $('toFromInput').value + ' ' + $('toFromInputCity').value + ' ' + country;
        gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale, getPolyline: true });
    },
    getHotelAddress: function() {
        var vcard = document.getElementsByClassName('vcard')[0];
        var name = vcard.getElementsByClassName('url fn org')[0].innerHTML;
        var haddress = vcard.getElementsByClassName('street-address')[0].innerHTML;
        var city = vcard.getElementsByClassName('locality')[0].innerHTML;
        var country = vcard.getElementsByClassName('country-name')[0].innerHTML;
        return (haddress + ' ' + city + ' ' + country);
    },
    getInTheAreaMarkers: function() {
        //var hotelAddress = this.getHotelAddress();
        //var address = [hotelAddress];
        //this.doGoogleRequests(address, 0)   
        var icon = new GIcon();
        icon.iconSize = new GSize(21, 57);
        icon.iconAnchor = new GPoint(10, 55);
        icon.image = '/images/map.arrow.big.gif';
        var point = new GLatLng($('googleMapsCoords').value.split(',')[0], $('googleMapsCoords').value.split(',')[1]);
        var marker = new GMarker(point, icon);
        mgr.addMarker(marker, 5);
        mgr.refresh();
        map.setCenter(point, 13);
    },
    doGoogleRequests: function(address, i, center) {
        if (address.length == i) {
            mgr.addMarkers(markers, 12);
            mgr.refresh();
        } else {
            var geocoder = new GClientGeocoder();
            geocoder.getLatLng(address[i],function(point) {
                var icon = new GIcon();
                icon.iconSize = i == 0 ? new GSize(21, 57) : new GSize(21, 21);
                icon.iconAnchor = i == 0 ? new GPoint(10, 55) : new GPoint(10, 21);
                icon.image = i == 0 ? '/images/map.arrow.big.gif' : '/images/map.arrow.small.gif';
                if (point)
                    markers.push(new GMarker(point, icon));
                else
                    throw (address[i] + " not found, while point is " + point);
                if (i == 0) map.setCenter(point, 13);
                broken.googleMaps.doGoogleRequests(address, ++i);
            });
        }
    },
    handleErrors: function(message) {
        if (typeof message == 'string')
            $('errorDirections').innerHTML = (message);
        else if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
            $('errorDirections').innerHTML = ("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
            $('errorDirections').innerHTML = ("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
            $('errorDirections').innerHTML = ("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_BAD_KEY)
            $('errorDirections').innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
            $('errorDirections').innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
        else $('errorDirections').innerHTML = ("An unknown error occurred." + message);
    }
}

broken.util = 
{
	addEvent : function(elem, event, func)
	{
		var elem = this.getElement(elem);
        
        if (elem.addEventListener)  // W3C DOM
            elem.addEventListener(event,func,false);
        else if (elem.attachEvent)  // IE DOM
            elem.attachEvent('on'+event, function(){ func(new broken.util.W3CDOM_Event(elem)) } );
            // for IE we use a wrapper function that passes in a simplified faux Event object.
        else throw 'cannot add event listener';
    },
    
    gotoPage : function(page)
    {
        if(typeof page == 'undefined')
            var page = window.location.href;
            
        window.location.href = page;
    },
    
    W3CDOM_Event : function(currentTarget)
    {
        this.currentTarget  = currentTarget;
        this.preventDefault = function() { window.event.returnValue = false }
        return this;
	},
	
	getElement : function(elem)
	{
	    if (document.getElementById) {
            if (typeof elem == "string") {
                elem = document.getElementById(elem);
                if (elem===null) throw 'cannot get element: element does not exist';
            } else if (typeof elem != "object") {
                throw 'cannot get element: invalid datatype';
            }
        } else throw 'cannot get element: unsupported DOM';
        return elem;
	},
	
	getY : function(o)
	{
	   var __y = 0;
       while( o != null ) {
            __y += o.offsetTop;
            o = o.offsetParent;
        }
        return __y;
	},
	
    getX : function(o)
	{
	   var __x = 0;
       while( o != null ) {
            __x += o.offsetLeft;
            o = o.offsetParent;
        }
        return __x;
	}
}

broken.xpath = 
{
    selectNodes : function(o, p, rn)
    {
         /** 
            USAGE: broken.xpath.selectNodes([xml object/node], [path(i.e. '/root', '/root/node'], [true or false]);           

            Syntax: /root/node, /root/node[searchValue], /root/node/[@id=123]           

            Gets singel xml node, if there's more then one with the same name the first one will be returned.
            o = xml object/xml node
            p = path
            rn = If ture, will return xml node insteed of node value
        **/


        // If rn is not set
        //if(typeof this.rn == 'undefined')
        this.rn = rn;       

        this.r = new Array();
        this.depth = 0;
        
        //Split in to an array
        this.path = p.split('/');

        //Get rid of empty, this is only due to syntax should look /root/node not root/node
        if(this.path[0] == '') this.path.shift(); 
        this.getNodes(o, this.path);       

        return this.r;    
    },

    

    getNodes : function(o, path)
    {
        // Needs better implemetation of recognition of []
        if(this.path[this.depth].indexOf('[') != -1)
        {
            var p = this.path[this.depth].split('[')[0];
            var s = this.path[this.depth].split('[')[1].split(']')[0];
        }else{
            var s = false;
            var p = this.path[this.depth];
        }        

        var rv = (this.depth + 1) == this.path.length? this.rn : true;   
        var n = this.findNodes(o, p, rv, s)        

        // Needs improvde check if n is empty or not
        try
        {
            if(this.depth == this.path.length || (n[0].firstChild.nodeType == 3 && n[0].childNodes.length == 1))
            {
                var node = n[0];
                if(rv)
                    this.r.push(node);
                else
                    this.r.push(node.firstChild.nodeValue);   
            }else if(n.length){
                this.depth++;
                for(var i = 0; i < n.length; i++)
                {
                    if(this.depth < this.path.length)
                        this.getNodes(n[i], path);
                    else if(rv && typeof n[i] != 'undefined')
                        this.r.push(n[i]);   
                }
                this.depth--;
            }        
        }catch(err){

            for(var i = 0; i < n.length; i++)
            {
                if(typeof n[i] != 'undefined')
                    this.r.push(n[i]);   
            }
        }
        // If length = 1 let's return a string/object insteed of an arrat
        //return node;   
    },    

    findNodes : function(o, n, rv, s)
    {
         /** 
		    Trying to find child nodes of o(xml object/node) named n(name)
    		Rreturn xml node if rv is true, else xml value
            Does ONLY check first level down
		**/         

        var a = new Array();
        var items = new Array();
        var nodeList = o.childNodes || o[0].childNodes; 		

		for(var i = 0; i < nodeList.length; i++)
		{
		    if(nodeList[i].nodeName == n)
		    {
		        /** I can't belive this worked, frackin' unbelievable! A real shoot inte the dark **/
		        var ts = (this.depth == (this.path.length - 1)) ? s : false;		        

			    var f = this.findNode(nodeList[i], true, ts);		    

			    if(typeof f != 'boolean') items.push(f);
		    }
		}		

    	if(items.length == 0) return false;
        if(items.length == 1 && rv) return items;		

		for(var i = 0; i < items.length; i++)
		{
		    if(items[i].nodeName == n)
		    {
			    var f = this.findNode(items[i], rv, s);
			    if(typeof f != 'boolean') a.push(f);
		    }
		}
        return a;
    }, 

	findNode : function(node, rv, s)
	{

		var r = rv ? node : node.firstChild.nodeValue;
		
		if(!s || s == node.firstChild.nodeValue) return r;        

        if(s.indexOf('=') != -1){
		    var attributes = s.split('@')[1].split('=');
			try{
				if(Prototype.Browser.IE)
				{
					if(node.attributes.getNamedItem(attributes[0]).nodeValue == attributes[1]) return r;
				}else{
					if(node.attributes[attributes[0]].nodeValue == attributes[1]) return r; 
				}
			}catch(err){}
		}else if(s.indexOf('@') != -1){
			var attributes = s.split('@')[1];
			try{
				if(Prototype.Browser.IE){
					if(node.attributes.getNamedItem(attributes).nodeValue) return rv ? r : node.attributes.getNamedItem(attributes).nodeValue;
				}else{
					if(node.attributes[attributes].nodeValue) return rv ? r : node.attributes[attributes].nodeValue;  
				}
			}catch(err){}
		}
		return false;
	}
}

broken.slideShowEngine = Class.create();
broken.slideShowEngine.prototype =
{
    initialize: function(arguments) {
        Object.extend(this, arguments);
        var _this = this;
        var data = new Ajax.Request(this.url, { onSuccess: _this.storeData.bind(this) });
    },
    storeData: function(data) {
        var x = data.responseXML;
        this.imageData = broken.xpath.selectNodes(x, this.path, true);
        this.imageArray = new Array();
        for (var i = 0; i < this.imageData.length; i++) {
            var imageObject = new broken.imageObject(this.imageData[i]);
            if (this.useAll)
                this.imageArray.push(imageObject);
            else if ($('hotelIdHidden').value == imageObject.hotelId)
                this.imageArray.push(imageObject);
        }
        this.bootup();
    },

    bootup: function() {
        this.currentPosition = this.firstCount();
        this.slideShowHolder0 = $(this.targetWrapper).getElementsByTagName('DIV')[0].id;
        this.slideShowHolder1 = $(this.targetWrapper).getElementsByTagName('DIV')[1].id;
        this._z = 101;
        this._last = $(this.slideShowHolder0);
        this.failsafe = false;
        if (Prototype.Browser.IE)
            $(this.slideShowHolder1).style.setAttribute('filter', 'alpha(opacity=0)');
        var _this = this;
        if (this.run)
            this.timeout = setTimeout(function() {
                _this.togglePictures('engine', 'next')
            }, 10000);
    },

    togglePictures: function(sender, direction) {
        if (this.failsafe) return;
        if (direction == 'next')
            ++this.currentPosition;
        else if (direction == 'previous')
            --this.currentPosition;
        this.failsafe = true;
        if (this.currentPosition >= (this.imageArray.length)) this.currentPosition = 0;
        if (this.currentPosition < 0) this.currentPosition = (this.imageArray.length - 1);
        for (x in this.imageArray[this.currentPosition])
            try {
            this[x] = this.imageArray[this.currentPosition][x];
        } catch (err) { }
        var last = this._last.id == $(this.slideShowHolder0).id ? $(this.slideShowHolder0) : $(this.slideShowHolder1);
        var next = last.id == $(this.slideShowHolder0).id ? $(this.slideShowHolder1) : $(this.slideShowHolder0);
        var _this = this;
        var duration = sender == 'human' ? 0.5 : 2.0;

        $(next.id).getElementsByTagName('IMG')[0].src = this.imagepath;
        $(next.id).style.zIndex = this._z;
        new Effect.Opacity($(next.id), {
            duration: duration,
            from: 0,
            to: 1.0,
            afterFinish: function() {
                if (Prototype.Browser.IE) {
                    $(last.id).style.setAttribute('filter', 'alpha(opacity=0)');
                } else {
                    $(last.id).style.opacity = '0';
                    $(next.id).style.opacity = '100';
                }
                _this.failsafe = false;
            }
        });
        if (typeof this.toggleAction != 'undefined')
            this.toggleAction();
        
        this._last = next;
        
        if (this._z > 400) {
            this._z = 101;
        } else {
            this._z = (this._z + 2);
        }
        
        var _this = this;
        this.timeout = setTimeout(function() {
            _this.togglePictures('engine', 'next')
        }, 10000);
    },
    firstCount: function() {
        var firstCount = this.findFirstImage();
        return firstCount >= (this.imageArray.length - 1) ? 0 : firstCount;
    },
    findFirstImage: function() {
        var imageInPage = $(this.targetWrapper).getElementsByTagName('IMG')[0].src;
        for (var i = 0; i < this.imageArray.length; i++)
            if (imageInPage.indexOf(this.imageArray[i].imagepath) != -1) return i;
        return 0;
    }
}

broken.imageObject = Class.create();
broken.imageObject.prototype = 
{
    initialize : function(data)
    {
        for(var i = 0; i < data.childNodes.length; i++){
            try{
                if(data.childNodes[i].nodeType == 1)
                    this[data.childNodes[i].nodeName] = data.childNodes[i].firstChild.nodeValue;
            }catch(err){}
        }
    }    
}
broken.util.addEvent(window, 'load', broken.page.initialize);


var quick = Class.create();

quick.search = {
    initialize: function(field_id) {
        this.field_id = field_id;
        this.resultLenght = 0;
        this.position = null;
        this.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE") + 5)) == 6;
        this.timeOut = null;

        $(field_id).setValue('');
        $('arrivalTime').setValue('');
        $('leavingTime').setValue('');

        var d = new Date();
        var minDate = new Date(d.getFullYear(), d.getMonth(), d.getDate());
        minDate.setDate(minDate.getDate() + minNights);

        $('arrivalTime').setValue(d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear());
        $('leavingTime').setValue(minDate.getDate() + '/' + (minDate.getMonth() + 1) + '/' + minDate.getFullYear());

        $(field_id).observe('blur', function(e) {
            if (quick.search.resultLength > 0 && quick.search.position != null) {
                quick.search.selectHotel($$('#quickbooking_results a')[quick.search.position].innerHTML.stripTags(), $$('#quickbooking_results a')[quick.search.position].href.split('?')[1]);
            }
        });

        $(field_id).observe('keydown', function(e) {
            if (e.keyCode == 13 || e.keyCode == 40 || e.keyCode == 38) {
                if (e.preventDefault) e.preventDefault();
                if (e.stopPropagation) e.stopPropagation();
            }
        });

        $(field_id).observe('keyup', this.look_for_hotel.bind(this));

        $('arrivalTime').observe('focus', function(e) {
            /*$('arrivalTime').setValue('');*/
            $$('.arrivalCalendar')[0].show();
        });

        $('arrivalTime').observe('keydown', function(e) {
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();

        });

//        $('arrivalTime').observe('blur', function(e) {
//            quick.search.onInputBlur(e, 'arrivalCalendar');
//        });

        $('leavingTime').observe('focus', function(e) {
            /*$('leavingTime').setValue('');*/
            $$('.departureCalendar')[0].show();
        });

        $('leavingTime').observe('keydown', function(e) {
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();
        });

//        $('leavingTime').observe('blur', function(e) {
//            quick.search.onInputBlur(e, 'departureCalendar');
//        });
    },

    look_for_hotel: function(e) {
        clearTimeout(this.timeOut);
        var min_search_length = 2;    // Search must have a least this number of chars
        var field_value = $(this.field_id).getValue();

        if ((field_value.length >= min_search_length || field_value.toLowerCase() == 'g') && (e.keyCode > 40 || e.keyCode == 0 || e.keyCode == 8)) {

            this.timeOut = setTimeout(function() {
                new Ajax.Request('/templates/public/widgets/QuickBookSearch.aspx', {
                    method: 'get',
                    parameters: { q: field_value, l: currentlanguage },
                    onComplete: function(transport) {
                        var response = transport.responseText;
                        quick.search.reset();
                        $('quickbooking_results').update(response);
                        if ($$('#quickbooking_results a').length > 0) {
                            if (quick.search.IE6) {
                                $$('#quickBookingHolder select').each(function(elem, index) {
                                    $(elem).hide();
                                });
                            }

                            $('quickbooking_results').show();

                            $$('#quickbooking_results a').each(function(elem, index) {
                                quick.search.resultLength++;
                                elem._index = index;
                                elem.observe('click', function(e) {
                                    e.preventDefault();
                                    quick.search.selectHotel(elem.innerHTML.stripTags(), elem.href.split('?')[1]);
                                });

                                elem.observe('mouseover', function(e) {
                                    if (quick.search.position != null) {
                                        $$('#quickbooking_results a')[quick.search.position].removeClassName('hover');
                                    }
                                    quick.search.position = this._index;
                                    $$('#quickbooking_results a')[quick.search.position].addClassName('hover');
                                });
                            });
                        } else {
                            quick.search.reset();
                        }
                    }
                });
            }, 300);
        } else if (e.keyCode == 13) {
            if (this.resultLength > 0 && this.position != null) {
                this.selectHotel($$('#quickbooking_results a')[this.position].innerHTML.stripTags(), $$('#quickbooking_results a')[this.position].href.split('?')[1]);
            }
        } else if (this.resultLength > 0 && (field_value.length >= min_search_length) && ((e.keyCode == 38) || (e.keyCode == 40))) {
            this.selectNext(e.keyCode);
        } else {
            this.reset();
        }
    },

    selectNext: function(_keyCode) {
        if (this.position == null) {
            this.position = 0;
        } else if (((this.position == (this.resultLength - 1)) && _keyCode == 40) || (this.position == 0 && _keyCode == 38)) {
            return;
        } else {
            $$('#quickbooking_results a')[this.position].removeClassName('hover');
            this.position = _keyCode == 40 ? this.position + 1 : this.position - 1;
        }
        $$('#quickbooking_results a')[this.position].addClassName('hover');
    },

    selectHotel: function(_string, _value) {
        $('hotelName').setValue(_string);
        $('ctl00_MainContentRegion_inputHotelId').setValue(_value);

        this.reset();
    },

    reset: function() {
        this.resultLength = 0;
        this.position = null;
        $('quickbooking_results').hide();

        if (quick.search.IE6) {
            $$('#quickBookingHolder select').each(function(elem, index) {
                $(elem).show();
            });
        }
    },

    onInputBlur: function(_event, _className) {
        var _blurEventTrigger = _event.explicitOriginalTarget || document.activeElement || e.relatedTarget;
        var _hideOnBlur = true;
        var _ancestorsArray = _blurEventTrigger.nodeType == 1 ? Element.extend(_blurEventTrigger).ancestors() : Element.extend(_blurEventTrigger.parentNode).ancestors();
        _ancestorsArray.each(function(item) {
            if ($(item).hasClassName('calender')) {
                _hideOnBlur = false;
            };
        })

        if (_hideOnBlur) {
            $$('.' + _className)[0].hide();
        }
    }

};

Event.observe(window, 'load', function() {
    if($('hotelName')){
        quick.search.initialize('hotelName');
    }
});
