
// we want to make sure that the hover state images don't need to load on the actual hover
var preload = [
    "/img/global/sitebar/link-hover-l.gif",
    "/img/global/sitebar/link-hover-r.gif",
    "/img/global/sitebar/dropdown-top.png",
    "/img/global/sitebar/dropdown-bottom.png",
    "/img/global/th3/subitem-bottom-border.gif"
];
setTimeout(function() {
    preload.each(function(img) {
        new Element('img', { 'src': (window.CRS) ? '/static'+img:img });
    });
}, 10);

document.observe('dom:loaded', function(e) {
    $$('ol#sitenav > li').each(function(el) {
        new Tablet.HoverElement(el, {hasActive:true, cssHover:true});
    });
    if ($('subnav')) {
        $$('ol#subnav li.hoverparent').each(function(el) {
            new Tablet.HoverElement(el);
        });
    }
    // this search thing is no longer here
    // var sitebar = $('sitebar');
    // if (sitebar) {
    //     var frm = sitebar.down('form.findlocation');
    //     if (frm) {
    //         var npt = frm.down('[name=ftl]');
    //         
    //         if (npt) {
    //             var sbmt = npt.next('input.hoverelement');
    //             if (sbmt) {
    //                 npt.observe('focus', function(e) {
    //                     sbmt.activate();
    //                 });
    //                 
    //                 npt.observe('blur', function(e) {
    //                     sbmt.deactivate();
    //                 });
    //             }
    //         }
    //     }
    // }
});

document.observe('dom:loaded', function(e) {
    new Tablet.Search.TextInput('finddestination', {
        url:'/javascript/LocationComplete',
        completer:'destinationcomplete',
        select:false
    });
});
Tablet = Tablet || {};

Tablet.Ajaxificator = Class.create({
    initialize: function(link) {
        this.link = $(link);
        this.options = Object.extend({
            auth: false,
            handle401:false,
            beforeStart: function() {},
            ajaxOptions: {}
        }, arguments[1] || {});

        this.initializeEvents();
    },
    initializeEvents: function() {
        Event.observe(this.link, 'click', this.clickHandler.bind(this));
    },
    unloadEvents: function() {
        Event.stopObserving(this.link, 'click');
    },
    clickHandler: function(event) {
        this.options.beforeStart.apply(this, []);
        if (!this.options.auth) {
            this.ajaxHandler();
        } else {
            this.authHandler();
        }
        event.stop();
    },
    deniedHandler: function(resp) {
        var message = '';
        if (resp.headerJSON && resp.headerJSON.message) {
            message = resp.headerJSON.message;
        }
        // check for message back from server
        
        Tablet.EnterSite.pane.page('loginForm', {
            onShow:function() {
                var action = {action:this.ajaxHandler.bind(this), args:[this]};
                Tablet.EnterSite.setManeuver(null, action); // sending null will create one automatically
            }.bind(this),
            message:message
        });
    },
    ajaxHandler: function() {
        var respFunctions = {};
        if (this.options.handle401) {
            respFunctions = {
                on401:this.deniedHandler.bind(this),
                on403:this.deniedHandler.bind(this)
            };
        }
        var options = Object.extend(respFunctions, this.options.ajaxOptions);
        new Ajax.Request(
            this.link.href, 
            options
        );
    },
    authHandler: function() {
        // man there's a lot of binding going on here
        Tablet.EnterSite.isRecognized({
            onSuccess:this.ajaxHandler.bind(this),
            onDenied:function(resp) {
                var message = '';
                // check for message back from server
                
                Tablet.EnterSite.pane.page('loginForm', {
                    onShow:function() {
                        var action = {action:this.ajaxHandler.bind(this), args:[this]};
                        Tablet.EnterSite.setManeuver(null, action); // sending null will create one automatically
                    }.bind(this)
                });
            }.bind(this)
        });
    }
});

/***************************************
** www/js/lastminutedeals/lastminutedeals.js
**
** generic functionality for last minute
** deals -- TabletHotels
** @author: Matthew Story
****************************************/
TH.lastminutedeals = {
    locations: [],
    //copy/paste from www/js/guides-results.js -- need a more elegant way to do this
    initMap:function() {
        Event.onGoogleLoad(TH.lastminutedeals.finishInitMap);
    },  
    finishInitMap: function() {
        TH.lastminutedeals.map = new Tablet.Map(($('googleMap')) ? "googleMap":'map');
        // place markers
        for (var i=0;i<TH.lastminutedeals.locations.length;i++) {
            TH.lastminutedeals.map.addPoint(TH.lastminutedeals.locations[i].lat, TH.lastminutedeals.locations[i].lng, (TH.lastminutedeals.locations.length > 1) ? i+1:null);
        }   
        TH.lastminutedeals.map.centerAndZoom();
    },
    loadAjaxifiers: function() {
        var scope = $(arguments[0]) || document;
        //set up tabs
        var mapView = ($('mapviewTab') && (scope == document || $('mapviewTab').descendantOf(scope))) ? $('mapviewTab'):false;
        if (mapView) {
            Tablet.Ajaxificator.makeAjaxificated($(mapView.getElementsByTagName('a')[0]), 'mapWrapper', TH.lastminutedeals.activateTab);
        }
        var rateView = ($('rateviewTab') && (scope == document || $('rateviewTab').descendantOf(scope))) ? $('rateviewTab'):false;
        if (rateView) {
            Tablet.Ajaxificator.makeAjaxificated($(rateView.getElementsByTagName('a')[0]), 'mapWrapper', TH.lastminutedeals.activateTab);
        }
        var viewHotelDetails = $A(scope.getElementsByClassName('viewHotelDetails')).concat($A(scope.getElementsByClassName('viewRoomDetails')));
        for (var i=0;i<viewHotelDetails.length;i++) {
            Tablet.Ajaxificator.makeAjaxificated(viewHotelDetails[i], 'detailBody', TH.lastminutedeals.activateDetail);
        }
        var detailTabs = scope.getElementsByClassName('detailnavitem');
        for (var i=0;i<detailTabs.length;i++) {
            Tablet.Ajaxificator.makeAjaxificated(detailTabs[i].getElementsByTagName('a')[0], 'detailBody', TH.lastminutedeals.activateDetail);
        }
        var timeLinks = scope.getElementsByClassName('timelinksWrapper');
        for (var i=0;i<timeLinks.length;i++) {
            Tablet.Ajaxificator.makeAjaxificated(timeLinks[i].getElementsByTagName('a')[0], 'mainwrapper', function() {return false;});
        }
        var currencyConverter = $('ratesIn')
        if (currencyConverter && (scope == document || currencyConverter.descendantOf(scope))) {
            Event.stopObserving(currencyConverter, 'click');
            Event.observe(currencyConverter, 'click', function(event) {
                Event.stop(event);
                var controlwrapper = this.up('.controlwrapper');
                if (TH.lastminutedeals.isActive(controlwrapper)) {
                    TH.lastminutedeals.deactivate(controlwrapper);
                    TH.lastminutedeals.changeValue('currencyOpen', 0);
                } else {
                    TH.lastminutedeals.activate(controlwrapper);
                    TH.lastminutedeals.changeValue('currencyOpen', 1);
                }
            }, true);
            if (!currencyConverter.selectbox) {
                currencyConverter.selectbox = new Tablet.SelectBox('currencySelector', {overwriteClickHandlers: false});
            }
            ((scope.select) ? scope.select('div#currencySelector a'):$$('div#currencySelector a')).each(function(e) {
                Tablet.Ajaxificator.makeAjaxificated(e, 'mainwrapper', function() {return false;}); 
            });
        }
    },
    getChangables: function() {
        return $A($$('ul#currenciesList a')).concat([$('dayOffset'), $('weekendView')])
    },
    changeValue: function(name, value, index) {
        TH.lastminutedeals.getChangables().each(function(e) {
            if (index != null) {
                var pattern = new RegExp('[&]*' + name + '[=][^&]*', 'g');
                var matches = e.href.match(pattern);
                e.href = e.href.replace(pattern, '');
                for (var i=0;i<matches.length;i++) {
                    if (i !== index) {
                        e.href += matches[i];
                    } else {
                        e.href += '&' + name + '=' + encodeURIComponent(value);
                    }
                }
            } else {
                e.href = e.href.replace(new RegExp(name + '[=][^&]*'), name + '=' + encodeURIComponent(value));
            }
        });
    },
    addValue: function(name, value) {
        TH.lastminutedeals.getChangables().each(function(e) {
            e.href = e.href + '&' + name + '=' + encodeURIComponent(value);
        });
    },
    removeValue: function(name, value, index) {
        TH.lastminutedeals.getChangables().each(function(e) {
            if (index != null) {
                var pattern = new RegExp('[&]*' + name + '[=][^&]*', 'g');
                var matches = e.href.match(pattern);
                e.href = e.href.replace(pattern, '');
                for (var i=0;i<matches.length;i++) {
                    if (i !== index) {
                        e.href = e.href + matches[i];
                    }
                }
            } else {
                e.href = e.href.replace(new RegExp('[&]*' + name + '[=]' + encodeURIComponent(value), 'g'), '');
            }
        });
    },
    getValueIndex: function(name, value) {
        var matches = $('dayOffset').href.match(new RegExp(name + '[=][^&]*', 'g'));
        for (var i=0;i<matches.length;i++) {
            if (matches[i].match(new RegExp(name + '[=]' + encodeURIComponent(value)))) {
                return i;
            }
        }
        return false;
    },
    isActive: function(elem) {
        return $(elem).className.match(/active/)
    },
    activateTab: function(elem) {
        elem = elem.parentNode
        if (TH.lastminutedeals.isActive(elem)) {
            return true;
        }
        $$('.main .controls')[0][(elem.id == 'mapviewTab') ? 'addClassName':'removeClassName']('map');
        $$('.hotellist')[0][(elem.id == 'mapviewTab') ? 'addClassName':'removeClassName']('map');
        $$('.controllinks')[0][(elem.id == 'mapviewTab') ? 'addClassName':'removeClassName']('maplinks');
        $A($$('.tablist li')).each(TH.lastminutedeals.deactivate);
        TH.lastminutedeals.activate(elem);
        TH.lastminutedeals.changeValue('displayMap', ($$('.hotellist')[0].hasClassName('map')) ? 1:0); 
        return (elem == $('rateviewTab') || $('googleMap'));
    },
    activateDetail: function(elem) {
        //if this is the view hotel details link
        var scope = elem.up('.hotellistitem') || elem.up('.roomlistitem');
        var field = (elem.up('.hotellist')) ? 'locationHotelId':'roomId';
        if (elem.className.match(/(viewHotelDetails)|(viewRoomDetails)|(viewdetails)/)) {
            var field = (elem.className.match(/viewHotelDetails/)) ? 'locationHotelId':'roomId';
            if (TH.lastminutedeals.isActive(scope)) {
                TH.lastminutedeals.deactivate(scope);
                if (elem.getAttribute('viewText')) {
                    elem.innerHTML = elem.getAttribute('viewText');
                }
                var value = elem.href.match(new RegExp(field + '[=][^&]*'))[0].replace(/.*[=]/, '');
                var index = TH.lastminutedeals.getValueIndex(field, value); 
                TH.lastminutedeals.removeValue(field, value); 
                TH.lastminutedeals.removeValue('detailType', elem.href.match(/detailType[=][^&]*/)[0].replace(/.*[=]/, ''), index);
                return true;
            } else {
                TH.lastminutedeals.activate(scope);
                TH.lastminutedeals.deactivateDetailNav(scope);
                var detailNav = scope.getElementsByClassName('detailNav')[0];
                TH.lastminutedeals.activate(((elem.className.match(/viewHotelDetails/)) ? detailNav.getElementsByClassName('description')[0]:detailNav.getElementsByClassName('room')[0]).getElementsByTagName('a')[0]);
                if (elem.getAttribute('hideText')) {
                    elem.innerHTML = elem.getAttribute('hideText');
                }
                TH.lastminutedeals.removeValue(field, 0);
                TH.lastminutedeals.removeValue('detailType', 0);
                TH.lastminutedeals.addValue(field, elem.href.match(new RegExp(field + '[=][^&]*'))[0].replace(/.*[=]/, ''));
                TH.lastminutedeals.addValue('detailType', elem.href.match(/detailType[=][^&]*/)[0].replace(/.*[=]/, ''));
                return false;
            }
        } else {
            if (TH.lastminutedeals.isActive(elem)) {
                return true;
            } else {
                TH.lastminutedeals.deactivateDetailNav(scope);
                TH.lastminutedeals.activate(elem);
                TH.lastminutedeals.changeValue('detailType', elem.href.match(/detailType[=][^&]*/)[0].replace(/.*[=]/, ''), TH.lastminutedeals.getValueIndex(field, elem.href.match(new RegExp(field + '[=][^&]*'))[0].replace(/.*[=]/, '')));
                return false;
            }
        }
    },
    activate: function(elem) {
        try {
            $(elem).addClassName('active');
        } catch(e) {
            console.log(e);
        }
    },
    deactivate: function(elem) {
        try {
            $(elem).removeClassName('active');
        } catch(e) {
            console.log(e);
        }
    },
    deactivateDetailNav: function(scope) {
        var lis = $(scope).getElementsByClassName('detailNav')[0].getElementsByTagName('li');
        for (var i=0;i<lis.length;i++) {
            var a = lis[i].getElementsByTagName('a')[0];
            if (a) {
                TH.lastminutedeals.deactivate(a);
            }
        }
    },
    getSectionByClassName: function(scope, section) {
        var elem = $(scope).getElementsByClassName(section)[0];
        return (elem) ? elem:(scope == document.body) ? false:TH.lastminutedeals.getSectionByClassName(scope.parentNode, section); 

    }
}
Event.onReady(function() {
    new Tablet.SelectBox('otherCitySelector', {onItemSelect: function(e) {document.location = e.href;}});
    TH.lastminutedeals.loadAjaxifiers();
});

Tablet.Ajaxificator.makeAjaxificated = function(elem, section, beforeStart) {
    if (!elem) {
        return false;
    }
    elem.setAttribute('href', elem.getAttribute('href').replace(/sectionUpdate[=][^&]*([&]|$)/g, '') + '&sectionUpdate='+section); 
    elem.ajaxificator = new Tablet.Ajaxificator(elem, {
        beforeStart: function() {
            var stop = beforeStart(elem);
            if (stop) {
                return true;
            }
            if (!$(section)) {
                section = TH.lastminutedeals.getSectionByClassName(elem, section);
            }
            $(section).innerHTML = '';
            $(section).addClassName('loading');
        },
        ajaxOptions: {
            evalScripts: true,
            onSuccess: function(response) {
                try {
                    $(section).removeClassName('loading');
                    $(section).innerHTML = response.responseText;
                    TH.lastminutedeals.loadAjaxifiers(section);
                    var scripts = response.responseText.match(/[<]script[^>]*[>]((.|\r|\n)+?)[<]\/script[>]/g) || [];
                    for (var i=0;i<scripts.length;i++) {
                        eval(scripts[i].replace(/([<]script[^>]*[>])|([<]\/script[>])/g, ''));
                    }
                } catch (e) {
                    console.log(e);
                }
            }
        }
    });
}

var Tablet = Tablet || {};
Tablet.Search = Tablet.Search || {};
Tablet.Search.Destination = Tablet.Search.Destination || {};

Tablet.Search.Destination.Name = (function() {
    var ftl, nameHint;
    var autoComplete;
    
    return {
        init:function(focus) {
            ftl = new Tablet.TextInput('findlocation', {choices:LocationsList});
            if (ftl && focus && !$('resultsmap')) { // that means we're not on the results page
                ftl.focus();
            }
        }
    };
})();

document.observe('dom:loaded', function(e) {
    Tablet.Search.Destination.Name.init((($('search')) ? true:false));
});
