/* 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();
    var onClickHandler=function(event){cabinetObject.switchMethod(event);};
    var i;
    for(i=0; i<this.drawers.length; i++){
        this.drawers[i].onclick = onClickHander;
    }
};

Cabinet.prototype.rollingSwitch = function(event){
    var evt = event || window.event;
    
    if(this.movingFlag){
        return;
    }
    
    var closingDrawerContent = this.getActiveDrawerContent();
    var shrinkingHeight = this.getDrawerContentHeight();
    var openingDrawer;
    
    var i;
    if(!window.addEventListener){
        for(i=0; i<this.drawers.length; i++){
            if( isDescendant(this.drawers[i], evt.srcElement) ){
                openingDrawer = this.drawers[i];
            }
        }
    } else {
        openingDrawer = event.currentTarget;
    }

    if(openingDrawer === null) {
        return;
    }

    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(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*************************/
/* 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*/
	}
}


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

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();

    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';
    var i;
    for(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';
        var i;
        for(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.showNoItemsState = function(){
    var contentEl = document.createElement('DIV');
    contentEl.className = 'noSavedItems';
    contentEl.innerHTML = this.getNoItemsMessage();
    this.addDrawerContent(this.savedItemsDrawer, contentEl);
};

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.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');
};

