
// 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
    });
});
/*  create dom element that doesn't make it to document to load these
    images when this file is loaded,
    which is early in the page load process */
var preload = $A([
    '/i/TH3HomeLogoBeta.gif',
    '/i/home-destination-link.gif',
    '/i/home-hotelname-link.gif',
    '/i/home-getaway-link.gif',
    '/i/home-localgetaway-link.gif',
    '/i/home-myreservations-link.gif',
    '/i/GreatHotelDeals.gif',
    '/i/homeTitleReserveHotel.gif',
    '/i/HomePageTabs.gif',
    '/i/NewsletterEnter.gif',
    '/i/JoinTabletPlus.gif',
    '/i/PlusViewMoreDetails.gif',
    '/i/PlusParticipatingHotels.gif'
]);
function preloadImages(imgs) {
    imgs.each(function(img) {
        new Element('img', { 'src':img });
    });
}

preloadImages(preload);

var Tablet = Tablet || {};
Tablet.Home = (function(){
    var splash, pageContainer, pageList, pageLinks, pages, selectedPage, splashXml;
    var fadeDuration = 0.4;
    
    var hidePage = function(pg, onHide) {
        new Effect.Fade(pg, {
            duration:fadeDuration,
            afterFinish:function(e) {
                e.element.addClassName('inactive');
                if (onHide) onHide();
            }
        });
    };
    var showPage = function(link, pg) {
        pageLinks.invoke('removeClassName', 'selected');
        link.addClassName('selected');
        new Effect.Appear(pg, {
            duration:fadeDuration
        });
        selectedPage = pg;
    };
    
    var loadPage = function(e) {
        var link = this;
        // check to see if page has already been fetched
        var existingPage = pages.find(function(pg) {
            return (pg.id == link.up('li').className);
        }, this);
        
        if(typeof s_account !== 'undefined'){
            // this is for omniture tracking of tab clicks ticket #7253
            var s=s_gi(s_account);    
            s.linkTrackVars='prop1';
            s.prop1 = this.parentNode.className;
            s.tl(this,'o','tab'+ACTIVE_PAGES[this.parentNode.className]);
        }
        if (existingPage) {
            if (existingPage != selectedPage) {
                existingPage.setStyle({display:'none'});
                existingPage.removeClassName('inactive');
                if (selectedPage) hidePage(selectedPage, function() { showPage(link, existingPage); });
                else showPage(link, existingPage);
            }
        } else {
            if (selectedPage) hidePage(selectedPage);
            new Ajax.Request(link.href+'&bust='+Tablet.buster(), {
                method:'get',
                onSuccess:setPageContent.bindAsEventListener(link),
                onFailure:function() {
                    // think about showing old page again
                }
            });
        }
        Event.stop(e);
    };
    
    var setPageContent = function(resp) {
        // TODO: loadPage should set the latest link clicked
        // and we should check here to make sure this is content for that page
        var link = this;
        
        var pageHtml = resp.responseText.replace('\n','');
        var newPage = $(DOM.Builder.fromHTML(pageHtml));
        newPage.setStyle({display:'none'});
        if (Prototype.Browser.IE) {
            setPseudoClasses(newPage);
        }
        Element.insert(pageContainer, newPage);
        
        pages = pageContainer.select('div.page');
        
        // give the images just a moment to load
        setTimeout(function() {
            showPage(link, newPage);
        }, 400);
    };
    
    var setPseudoClasses = function(el) {
        el.select('ul li:first-child').invoke('addClassName', 'first-child');
        el.select('ul li:last-child').invoke('addClassName', 'last-child');
    };
    
    var insertHotelImage = function(resp) {
        if (!resp.responseXML) return;
        var doc = resp.responseXML;
        var album = doc.documentElement.getElementsByTagName('album');
        if (album.length > 0) {
            var rootPath = album[0].getAttribute('lgPath');
            imgs = doc.documentElement.getElementsByTagName('img');
            if (imgs.length > 0) {
                var img = imgs[0];
                var caption = new Element('span', {'class':'caption'}).
                    update(img.getAttribute('caption'));
                var hotel = new Element('img', {src:rootPath + img.getAttribute('src'), 
                    alt:img.getAttribute('caption')});
                var link = new Element('a', {href:img.getAttribute('link'), 'class':'featured'})
                    .update(hotel);
                Element.insert(link, {top:caption});
                Element.insert(splash, {top:link});
            }
            // splash.down('object').remove();
        }
    };
    
    var getSplashXml = function() {
        if (Tablet.Home.xmlfile) {
            new Ajax.Request(Tablet.Home.xmlfile, {
                method:'get',
                onSuccess:insertHotelImage
            });
        }
    };
    
    return {
        getSplashXml : function() { 
            getSplashXml();
        },
        init : function() {
            splash = $('splash');
            pageList = $('pages');
            pageLinks = pageList.select('li a');
            var tabWidth = 0, li, tabWidth;
            pageLinks.each(function(tab) {
                li = tab.up('li');
                tabWidth += li.getWidth() + parseInt(li.getStyle('marginLeft').replace('px', '')) + 
                    parseInt(li.getStyle('marginRight').replace('px', ''));
            });
            var tabPadding = Math.round((pageList.getWidth() - tabWidth) / 2)-1;
            pageList.setStyle({
                'paddingLeft':tabPadding+'px',
                'paddingRight':tabPadding+'px',
                'width':(pageList.getWidth() - (tabPadding*2))+'px'
            });
            
            pageLinks.each(function(link){
                link.observe('click', loadPage.bindAsEventListener(link));
            });
            
            pageContainer = $('content').down('div.main');
            pages = pageContainer.select('div.page');
            
            selectedPage = pageContainer.down('div.page');
            
            if (Prototype.Browser.IE) {
                var newsletterSignup = $('newsletter-signup');
                if (newsletterSignup && newsletterSignup.down('input.enter')) {
                    newsletterSignup.down('input.enter').observe('mouseover', function(e) { 
                        this.addClassName('hover');
                    });
                    newsletterSignup.down('input.enter').observe('mouseout', function(e) { 
                        this.removeClassName('hover');
                    });
                }
                
                setPseudoClasses(selectedPage);
            }
            
            if (!hasFlash) {
                splash.removeClassName('hasflash');
                splash.addClassName('static');
                getSplashXml();
            }
        }
    };
})();

var hasFlash = true;
if (swfobject) {
    if (swfobject.getFlashPlayerVersion().major <= 0) {
        hasFlash = false;
    }
}
document.observe('dom:loaded', function() {
    Tablet.Home.init();
});