/* Author: esmiling@condenet.com */

/* Drawers Base
    ------------ */
    function Cabinet(args){
        var cabinetObject =this;
        this.args = args;
        this.cabinet = document.getElementById(this.args.cabinet_id);
        this.drawers = getElements('drawer', 'DIV', this.cabinet);
        window.setTimeout(function(){cabinetObject.initialize();},0);    
    }
    Cabinet.prototype.initialize = function(){
        var cabinetObject = this;
        var switchType = this.args.switch_type || 'simple';
        this.switchMethod = this.rollingSwitch;
        this.drawerContentHeight = this.getDrawerContentHeight();
        for(var i=0; i<this.drawers.length; i++)
            this.drawers[i].onclick = function(event){cabinetObject.switchMethod(event)};
    }
    Cabinet.prototype.rollingSwitch = function(event){
        var evt = event || window.event;
        if(this.movingFlag) return;
        var closingDrawerContent = this.getActiveDrawerContent();
        var shrinkingHeight = this.getDrawerContentHeight();
        var openingDrawer;
        if(!window.addEventListener){
            for(var i=0; i<this.drawers.length; i++)
                if( isDescendant(this.drawers[i], evt.srcElement) ) openingDrawer = this.drawers[i];
        }
        else openingDrawer = event.currentTarget;
        var openingDrawerContent = getElements('drawer_content', 'DIV', openingDrawer)[0];
        var growingHeight = 0;
        var speed = this.args.speed || 6;
        var cabinetObject = this;
        if(closingDrawerContent == openingDrawerContent) return;
        closingDrawerContent.className += ' closing';
        openingDrawerContent.className += ' opening';
        for(var i=0; i<cabinetObject.drawers.length; i++)
            cabinetObject.drawers[i].className = cabinetObject.drawers[i].className.replace('opened', 'closed');
        openingDrawer.className = openingDrawer.className.replace('closed', 'opened');
        this.movingFlag = true;
        var clearer = setInterval( function(){
            closingDrawerContent.style.height = shrinkingHeight + 'px';
            openingDrawerContent.style.height = growingHeight + 'px';
            if(shrinkingHeight - speed >= 0){
                shrinkingHeight -= speed;
                growingHeight += speed;
            }else{
                clearInterval(clearer);
                closingDrawerContent.style.height = 0;
                openingDrawerContent.style.height = cabinetObject.drawerContentHeight + 'px';
                closingDrawerContent.className = closingDrawerContent.className.replace('closing', '');
                openingDrawerContent.className = openingDrawerContent.className.replace('opening', '');
                cabinetObject.movingFlag = false;
            }
        },10);
    }
    Cabinet.prototype.getDrawerContentHeight = function(){
        var openedDrawerContent = this.getActiveDrawerContent();
        return openedDrawerContent.offsetHeight;
    }
    Cabinet.prototype.getActiveDrawer = function(){return getElements('opened', 'DIV', this.cabinet)[0];}
    Cabinet.prototype.getActiveDrawerContent = function(){
        var openedDrawer = this.getActiveDrawer();
        var openedDrawerContent = getElements('drawer_content', 'DIV', openedDrawer)[0];
        return openedDrawerContent;
    }
/*********************END DRAWERS BASE*************************/

/* set global var for showNoTripsState function to access for holiday gift guide */
var user_name = "";

/*  MyConcierge Widget (Callback to turn data returned from the ajax call into a set of drawers)
    --------------------------------------------------------------------------------- */
        function MyConciergeWidget(data){  //callback
            this.widgetEl = document.getElementById('myConcierge_widget');
            this.userInfo = data.userInfo;
            this.trips = data.groups;
            this.savedItems = data.items;
            this.location = data.location;
            this.destUrlName = data.destUrlName;
            this.itemCount = data.itemCount;
            this.init( );
            this.shareData( );/*move to jsp*/
        }
        MyConciergeWidget.prototype.shareData = function( ){
            addCount( 'lnSvdItemsCt', this.itemCount);/*move to jsp*/
            if(hasActionUi) instantiateActionManager( this.trips);/*move to jsp*/
        }
        MyConciergeWidget.prototype.init = function(){
            var mcw = this;
            this.writeUserInfo( );
            if(this.trips.length == 0){		
                this.showNoTripsState( );
                return;
            }
			/* Comment out or remove else statement below after the holidays when holiday gift guides is removed. */
			else{
				document.getElementById('myConcierge_widget').style.display = 'block';
			}
            this.writeCabinet( );
            if(window.addEventListener)
                addEventListener('unload', function( ){mcw.saveActiveDrawer( )}, true)
            if(window.attachEvent)
                window.attachEvent('onunload', function( ){mcw.saveActiveDrawer( )})
        }
        MyConciergeWidget.prototype.writeUserInfo = function(){
            var iconId, userNameId, iconClass, loadingIconEl, userPhotoEl, userNameEl, userName, userBadgePath, defaultUserPhotoPath;
			iconId = 'mcw_userPhoto';
			iconClass = 'userPhoto';
			userNameId ='mcw_username';
            userName = this.userInfo.userName;
			userBadgePath = this.userInfo.userPhotoPath;
            if(userName.length > 20) userName = userName.substring(0, 20) + '&#133;';
            loadingIconEl = document.getElementById(iconId);
			userNameEl = document.getElementById(userNameId);
			userPhotoEl = new Image( );
			userPhotoEl.className = iconClass;
			userPhotoEl.id = iconId;
            userPhotoEl.src = userBadgePath;
			try{loadingIconEl.parentNode.replaceChild(userPhotoEl, loadingIconEl);}
            catch(e){
                loadingIconEl.src = userBadgePath;
                loadingIconEl.className = iconClass;
            }
            userNameEl.innerHTML = userName;
			
			user_name = userName;
        }
        MyConciergeWidget.prototype.writeCabinet = function(){
            var isFiltered, savedItemsTitlePrefix;
            isFiltered = (this.location ? true : false);
            savedItemsTitlePrefix = (isFiltered ? 'My ' + this.location : 'All'); 
            this.cabinetEl = document.createElement('DIV');
            this.cabinetEl.className = 'cabinet'
            this.cabinetEl.id = 'myConcierge_cabinet';
            this.cabinetEl.style.display = 'none'; //test
            this.tripsDrawer = this.getDrawerEl('My Trip Plans');
            this.savedItemsDrawer = this.getDrawerEl(savedItemsTitlePrefix + ' Saved Items (' + this.itemCount + ')');
            this.cabinetEl.appendChild(this.tripsDrawer);
            this.cabinetEl.appendChild(this.savedItemsDrawer);
            this.widgetEl.appendChild(this.cabinetEl);
            this.writeTripList( );
            this.writeSavedItemList( );	
	    	
			/* remove or comment out function call below to turn off holiday gift guide 2009 */
			this.writeHolidayGiftGuideLink( );
            
			if( isFiltered && this.savedItems.length>0) this.addAllItemsLink( );		
            this.setActiveDrawer(  )
            new Cabinet({cabinet_id: 'myConcierge_cabinet', speed: 20}); //instance of cabinet object above
            this.cabinetEl.style.display = 'block';
        }
        MyConciergeWidget.prototype.getDrawerEl = function(headlineText){
            var drawerEl, headlineEl, drawerContentEl;
            drawerEl = document.createElement('DIV');
            drawerEl.className = 'drawer';
            headlineEl = document.createElement('H4');
            headlineEl.innerHTML = headlineText;
            drawerContentEl = document.createElement('DIV');
            drawerContentEl.className = 'drawer_content';
            drawerEl.appendChild(headlineEl);
            drawerEl.appendChild(drawerContentEl);
            return drawerEl;
        }
        MyConciergeWidget.prototype.addAllItemsLink = function(){
                var allLink = document.createElement('A');
                allLink.className = 'moreLink'
                allLink.href = '/travelguide/' + this.destUrlName + '/myitems';
                allLink.innerHTML = "See all " + this.location + ' Saved Items&nbsp;&#8250;';
                this.addDrawerContent(this.savedItemsDrawer, allLink);
        }
        MyConciergeWidget.prototype.addAllTripsLink = function(){
                var allLink = document.createElement('A');
                allLink.className = 'moreLink'
                allLink.href = '/myconcierge/trips/mostrecent/'
                allLink.innerHTML = "See all Trip Plans&nbsp;&#8250;";
                this.addDrawerContent(this.tripsDrawer, allLink);
        }
        MyConciergeWidget.prototype.addDrawerContent = function(drawerEl, htmlElementNode){ //temp
            var drawerContentEl = getElements('drawer_content', null, drawerEl)[0];
            drawerContentEl.appendChild(htmlElementNode);
        }
        MyConciergeWidget.prototype.writeTripList = function( ){ //consolidate
            this.tripListEl = document.createElement('UL');
            this.tripListEl.className = 'slateList';
            this.tripListEl.id = 'mcw_tripList';
            for(var i=0; i<this.trips.length; i++)
                new WidgetItem({
                    parentEl: this.tripListEl,
                    title: this.trips[i].groupTitle,
                    path: '/myconcierge/trips/' + this.trips[i].groupId,
                    count: this.trips[i].itemCount
                });
            this.addDrawerContent(this.tripsDrawer, this.tripListEl);
            this.addAllTripsLink();
        }
        MyConciergeWidget.prototype.writeSavedItemList = function(){ //consolidate
            if(this.savedItems.length > 0){
                this.savedItemListEl = document.createElement('UL');
                this.savedItemListEl.className = 'slateList';
                this.savedItemListEl.id =  'mcw_savedItemsList';
                for(var i=0; i<this.savedItems.length; i++)
                    new WidgetItem({
                        parentEl: this.savedItemListEl,
                        title: this.savedItems[i].itemTitle,
                        path: this.savedItems[i].itemPath
                    });
                this.addDrawerContent(this.savedItemsDrawer, this.savedItemListEl);
            }
            else this.showNoItemsState( );
        }
		
		MyConciergeWidget.prototype.writeHolidayGiftGuideLink = function(){		
		  /* set hggWrapper to display none */
  		  var hggWrapperEl = document.getElementById('hggWrapper');	
		  hggWrapperEl.style.display = 'none';
		    var myConciergeCabinetEl = document.getElementById('myConcierge_cabinet');	
	        var holidayGiftGuideEl = document.createElement('DIV');
		    holidayGiftGuideEl.className = 'sectionhead';
	        holidayGiftGuideEl.id = 'mcw_log_invitation';
		    holidayGiftGuideEl.innerHTML = "<p>Check out our <a href='/promo/holiday_gift/' target='_blank'>Holiday Gift Guide</a></p>";
		    myConciergeCabinetEl.appendChild(holidayGiftGuideEl);
        }
		
		
        MyConciergeWidget.prototype.showNoItemsState = function(){
            var contentEl = document.createElement('DIV');
            contentEl.className = 'noSavedItems';
            contentEl.innerHTML = this.getNoItemsMessage( );
            this.addDrawerContent(this.savedItemsDrawer, contentEl);
        }
        
		/* Commenting out original function definition for holiday gift guide implementation.
		MyConciergeWidget.prototype.showNoTripsState = function( ){
           var contentEl = document.createElement('DIV');
           contentEl.className = 'noTrips content';
           contentEl.id = 'mcw_noTrips';
           contentEl.innerHTML = this.getNoTripsMessage( );
           this.widgetEl.appendChild(contentEl);
        } 
		*/
		
		MyConciergeWidget.prototype.showNoTripsState = function( ){
			var hggWrapperEl = document.getElementById('hggWrapper');			
			var welcomeEl = document.createElement('DIV');
			welcomeEl.className = 'sectionhead';
	        welcomeEl.id = 'mcw_invitation';		
		    welcomeEl.innerHTML = "<p>Welcome&nbsp;<a href='/myconcierge/profile'>" + user_name + "</a>&nbsp;&nbsp;<span>|</span>&nbsp;&nbsp;" + 
				"<a href='/myconcierge/trips/mostrecent'>Create a trip</a>&nbsp;&nbsp;<span>|</span>&nbsp;&nbsp;" + 
				"<a href='/user/signout'>Sign out</a></p>";
			hggWrapperEl.style.marginBottom =  "17px";
		    hggWrapperEl.appendChild(welcomeEl);
			hggWrapperEl.style.display = 'block';
        }
				
		MyConciergeWidget.prototype.getNoTripsMessage = function(){
            return '<h5>Planning a trip? Start here.</h5>' +
						'<div id="mcw_join_invitation">' +
                            '<ul>' +
                                '<li>Save the information you find while researching your next vacation</li>' +
                                '<li>Create a Trip Plan with your favorite hotels, restaurants, and more</li>' +
                                '<li>Upload and share photos with fellow travelers</li>' +
                            '</ul>' +
							'<span class="moreLink"><a href="/myconcierge/trips/learnmore">Learn More</a>&nbsp;&#8250;</span>' +
                            '<div class="clearer"></div>' +
						'</div>';
        }	
		
        MyConciergeWidget.prototype.getNoItemsMessage = function(){
            return "<h5>You haven't saved any items here yet.</h5>" +
                        'As you browse Concierge.com, look for things that interest you&#151;hotels, restaurants, photos, articles&#151;and click the "Save for Later" button to store them in one of your Trip Plans.'
        }
        MyConciergeWidget.prototype.saveActiveDrawer = function( ){
            var activeDrawer = this.getActiveDrawer( );
            document.cookie = 'mwactive=' + activeDrawer + '; max-age=' + 60*60*24*365 + '; path=/';
        }
        MyConciergeWidget.prototype.setActiveDrawer = function( ){
            var activeDrawer, activeDrawerEl, inactiveDrawerEl;
            activeDrawer = getCookie('mwactive') || 'default';
            activeDrawerEl = ( activeDrawer == 'saveditems' || activeDrawer == 'default' ? this.savedItemsDrawer : this.tripsDrawer )
            inactiveDrawerEl = ( activeDrawerEl == this.tripsDrawer ? this.savedItemsDrawer : this.tripsDrawer )
            activeDrawerEl.className += ' opened'
            inactiveDrawerEl.className += ' closed';
        }
        MyConciergeWidget.prototype.getActiveDrawer = function( ){
            var activeDrawerEl = getElements('opened', null, this.cabinetEl)[0];
            return ( activeDrawerEl == this.tripsDrawer ? 'trips' : 'saveditems');
        }

    /* Widget Item: 
        ----------- */
        function WidgetItem(args){
            this.title = args.title;
            this.path = args.path;
            this.parentEl = args.parentEl;
            this.count = args.count || null;
            this.writeItem();
        }
        WidgetItem.prototype.writeItem = function(){
            var linkEl, itemEl;
            linkEl = document.createElement('A');
            itemEl = document.createElement('LI');
            linkEl.href = this.path;
            linkEl.innerHTML = this.title;
            if(this.count) linkEl.innerHTML += '&nbsp;(' + this.count + ')'
            itemEl.appendChild(linkEl);
            this.parentEl.appendChild(itemEl);
        }
/***END MYCONCIERGE WIDGET***/

function showWidgetNotLogged( ){
    var notLoggedWidget = document.getElementById('mcw_notLogged');
    notLoggedWidget.style.display = 'block';
    document.getElementById('myConcierge_widget').style.display = 'none';
    addCount('lnSvdItemsCt', 0);
    if(hasActionUi)
		instantiateActionManager( null ); /*move to jsp*/
}

