﻿
//
// Tabs
//

PhotoSite.TabsPanelTabs = function(containerDomElement, onTabChangedCallback, onTabClickedCallback) {
    this._tabs = [];
    this._container = containerDomElement;
    this._clickDelegate = Function.createDelegate(this, this._selectTab);
    this._tabChangedCallback = onTabChangedCallback;
    this._tabClickedCallback = onTabClickedCallback;
};

PhotoSite.TabsPanelTabs.prototype = {
    _tabs: null,
    _container: null,
    _clickDelegate: null,
    _tabChangedCallback: null,
    _tabClickedCallback: null,
    _selectedTab: null,

    addTab: function(name, image, imageSelected) {
        var tabImg = document.createElement('img');
        var tabObj = { Name: name, Image: image, ImageSelected: imageSelected, DOMImage: tabImg };

        if (this._tabs.length === 0) {
            tabImg.src = imageSelected;
            this._selectedTab = tabObj;
        }
        else {
            tabImg.src = image;
        }

        tabImg.obj = tabObj;
        tabImg.parentObj = this;
        tabImg.style.cursor = 'pointer';

        if (-1 != navigator.userAgent.indexOf("MSIE"))
            tabImg.style.height = '27.4px';

        tabImg.onclick = function() { this.parentObj._clickDelegate(this); };

        this._container.appendChild(tabImg);
        this._tabs.push(tabImg.obj);
    },

    selectTabByName: function(name) {
        for (var i = 0; i < this._tabs.length; i++) {
            if (this._tabs[i].Name == name) {
                this._selectTab(this._tabs[i].DOMImage);
                break;
            }
        }
    },

    _selectTab: function(img) {
        if (this._tabClickedCallback !== 'undefined' && this._tabClickedCallback !== null) {
            this._tabClickedCallback(this._selectedTab.Name);
        }

        if (this._selectedTab != img.obj) {
            this._selectedTab.DOMImage.src = this._selectedTab.Image;
            this._selectedTab = img.obj;
            this._selectedTab.DOMImage.src = this._selectedTab.ImageSelected;

            if (this._tabChangedCallback !== 'undefined' && this._tabChangedCallback !== null) {
                this._tabChangedCallback(this._selectedTab.Name);
            }
        }
    }
};

//
// Panel
//

var albumsCount = 0;

PhotoSite.TabsPanel = function(ID, showProjectsTab, showDocumentsTab) {
    this._id = ID;
    this._onProjectChangedDelegate = Function.createDelegate(this, this._onProjectChanged);
    this._onAlbumChangedDelegate = Function.createDelegate(this, this._onAlbumChanged);
    this._onTabChangedDelegate = Function.createDelegate(this, this._onTabChanged);
    this._onTabClickedDelegate = Function.createDelegate(this, this._onTabClicked);
    this._onSectionChangedDelegate = Function.createDelegate(this, this._onSectionChanged);
    this._tabs = new PhotoSite.TabsPanelTabs(document.getElementById(ID + '_domTabs'), this._onTabChangedDelegate, this._onTabClickedDelegate);

    this._tabs.addTab('albums', '/images/tools/tab_side_albums.gif', '/images/tools/tab_side_albums_on.gif');
    this._albumsList = new PhotoSite.TabsPanelList(document.getElementById(ID + '_domAlbumsScrollBox'), 'album_listin2', 'album_listing');

    if (showProjectsTab) {
        this._tabs.addTab('projects', '/images/tools/tab_side_projects.gif', '/images/tools/tab_side_projects_on.gif');

        this._projectList = new PhotoSite.TabsPanelList(document.getElementById(ID + '_domProjectScrollBox'), 'album_listing2', 'album_listing');
        this._projectListPhotoBooks = this._projectList.addSection('PhotoBooks', SR.MyPhotoBooks, this._onSectionChangedDelegate, '');
        //this._projectListCalendars = this._projectList.addSection('Calendars', SR.MyCalendars, this._onSectionChangedDelegate);
        this._projectListShared = this._projectList.addSection('SharedPhotoBooks', SR.SharedWithYou, this._onSectionChangedDelegate, '');
    }

    if (showDocumentsTab) {
        this._tabs.addTab('documents', '/images/login/tab_orange_documents' + SR.LanguageSuffix + '.gif', '/images/login/tab_orange_documents' + SR.LanguageSuffix + '_on.gif');
    }

    this._albumsService = new IAlbumService();

    this._albumsService.GetUserAlbums2(addAlbumTabSections, gotError);
    this._albumsService.GetUserProjects2(addProjectTabSections, gotError);

    this._albumsListUpload = this._albumsList.addSection('AlbumUpload', SR.MyAlbums, this._onSectionChangedDelegate, '');
    this._albumsListShared = this._albumsList.addSection('AlbumShared', SR.MySharedAlbums, this._onSectionChangedDelegate, '2');
    this._albumsListFriend = this._albumsList.addSection('AlbumFriend', SR.SharedWithYou, this._onSectionChangedDelegate, '');

};


function addAlbumTabSections(albumList) {
    var myAlbumText = $get("sectionTabAlbumUpload");
    var mySharedAlbumText = $get("sectionTabAlbumShared");
    var myFriendsAlbumText = $get("sectionTabAlbumFriend");

    if (mySharedAlbumText)
        mySharedAlbumText.innerHTML = SR.MySharedAlbums + ' (' + getObjectsByType(albumList, 'Share') + ')';
    if (myAlbumText)
        myAlbumText.innerHTML = SR.MyAlbums + ' (' + getObjectsByType(albumList, 'Upload') + ')';
    if (myFriendsAlbumText)
        myFriendsAlbumText.innerHTML = SR.SharedWithYou + ' (' + getObjectsByType(albumList, 'Friend') + ')';

}

function addProjectTabSections(projectList) {
    var myProjectsText = $get("sectionTabPhotoBooks");
    var mySharedProjectsText = $get("sectionTabSharedPhotoBooks");

    if (myProjectsText)
        myProjectsText.innerHTML = SR.MyPhotoBooks + ' (' + getObjectsByType2(projectList, 'PhotoBook') + ')';
    if (mySharedProjectsText)
        mySharedProjectsText.innerHTML = SR.SharedWithYou + ' (' + getObjectsByType2(projectList, 'SharedPhotoBook') + ')';


}

function getObjectsByType(albums, type) {
    var count = 0;
    for (var i = 0; i < albums.length; i++) {
        var album = albums[i];
        if (album.Type == type)
            count++;
    }
    return count;
}

//function getObjectsByType2(photobooks) {
//    var count = 0;
//    for (var i = 0; i < photobooks.length; i++) {
//            count++;
//    }
//    return count;
//}

function getObjectsByType2(photobooks, type) {
    var count = 0;
    for (var i = 0; i < photobooks.length; i++) {
        var photobook = photobooks[i];
        if (photobook.Type == type)
            count++;
    }
    return count;
}

PhotoSite.TabsPanel.prototype = {
    _id: null,
    _tabs: null,
    _albumsService: null,
    _albumsList: null,
    _albumsListUpload: null,
    _albumsListShared: null,
    _albumsListFriend: null,
    _projectList: null,
    _projectListPhotoBooks: null,
    _projectListCalendars: null,
    _projectListShared: null,

    _manager: null,
    _currentTab: null,
    _uploadUrl: null,

    _onTabChangedDelegate: null,
    _onTabChangedCallback: null,

    _onTabClickedDelegate: null,
    _onTabClickedCallback: null,

    _onAlbumChangedDelegate: null,
    _onAlbumChangedCallback: null,

    _onProjectChangedDelegate: null,
    _onProjectChangedCallback: null,

    _onSectionChangedDelegate: null,
    _onSectionChangedCallback: null,

    _userAlbums: null,
    _userProjects: null,
    _userDocuments: null,

    getCurrentTab: function() {
        var sender = querySt('tab');
        if (typeof sender != 'undefined' && sender != null)
            this._currentTab = sender;
        return this._currentTab !== null ? this._currentTab : 'albums';
    },

    setCurrentTab: function(name) {
        if (this.getCurrentTab() == name) {
            this._tabs.selectTabByName(name);
            this._onTabChanged(name);
        } else {
            this._tabs.selectTabByName(name);
        }
    },

    setUploadUrl: function(url) {
        this._uploadUrl = url;
    },

    onUploadButtonClick: function() {
        var uploadUrl = this._uploadUrl;
        var currentUrl = location.href;

        var index = currentUrl.indexOf('#', 0);

        if (index > 0) {
            currentUrl = currentUrl.substring(0, index);
        }

        index = currentUrl.indexOf('tab=');

        if (index > 0) {
            currentUrl = currentUrl.substring(0, index - 1);
        }

        if (uploadUrl.indexOf('?') > 0) {
            uploadUrl += '&';
        }
        else {
            uploadUrl += '?';
        }

        location.href = uploadUrl + 'referrer=' + escape(currentUrl + '?tab=' + this.getCurrentTab());
    },
    
    showCreateNewAlbum: function(show) {
        document.getElementById(this._id + '_domCreateNewAlbum').style.display = show ? '' : 'none';
    },

    setOnTabChangedCallback: function(callbackFunction) {
        this._onTabChangedCallback = callbackFunction;
    },

    setOnTabClickedCallback: function(callbackFunction) {
        this._onTabClickedCallback = callbackFunction;
    },

    setOnSectionChangedCallback: function(callbackFunction) {
        this._onSectionChangedCallback = callbackFunction;
    },

    populateAlbums: function() {
        this._albumsService.GetUserAlbums2(Function.createDelegate(this, this._onGotUserAlbums), gotError);
    },

    populateProjects: function() {
        this._albumsService.GetUserProjects2(Function.createDelegate(this, this._onGotUserProjects), gotError);
    },

    populateDocuments: function() {
        this._albumsService.GetUserDocuments2(Function.createDelegate(this, this._onGotUserDocuments), gotError);
    },

    _onTabClicked: function(name) {
        if (this._onTabClickedCallback !== null) {
            this._onTabClickedCallback(name);
        }
    },

    _showHideContainer: function(container, show) {
        var element = document.getElementById(this._id + '_dom' + container + 'Container');

        if (element !== null) {
            element.style.display = show ? '' : 'none';
        }
    },

    _onTabChanged: function(name) {
        this._showHideContainer('Albums', name == 'albums');
        this._showHideContainer('Projects', name == 'projects');
        this._showHideContainer('Documents', name == 'documents');

        if (name == 'albums' && this._userAlbums === null) {
            this.populateAlbums();
        }
        else if (name == 'projects' && this._userProjects === null) {
            this.populateProjects();
        }
        else if (name == 'documents' && this._userDocuments === null) {
            this.populateDocuments();
        }

        if (this._onTabChangedCallback !== null) {
            this._onTabChangedCallback(name);
        }

        this._currentTab = name;
    },

    _onSectionChanged: function(section) {
        if (this._onSectionChangedCallback) {
            this._onSectionChangedCallback(section);
        }
    },

    _onGotUserDocuments: function(result) {
        this._userDocuments = result;
        this._populateDocumentsTabs();
        this._onTabChanged('documents');
    },

    _populateDocumentsTabs: function() {
        RadixSort.sortByKey(this._userDocuments, 'Year');

        var lastYear = null;
        var scrollbox = document.getElementById(this._id + '_domDocumentsScrollBox');
        scrollbox.innerHTML = '';

        for (var i = 0; i < this._userDocuments.length; i++) {
            var doc = this._userDocuments[i];

            if (doc.Year != lastYear) {
                var yearHeader = document.createElement('div');
                yearHeader.innerHTML = '<strong>' + doc.Year + '</strong>';
                yearHeader.style.color = '#707172';
                yearHeader.style.height = '20px';
                yearHeader.style.paddingLeft = '15px';
                scrollbox.appendChild(yearHeader);
                lastYear = doc.Year;
            }

            var docDiv = document.createElement('div');
            docDiv.innerHTML = doc.Name;
            docDiv.style.paddingLeft = '20px';
            scrollbox.appendChild(docDiv);
        }
    },

    _onGotUserProjects: function(result) {
        this._userProjects = result;

        this._populateProjectTabs();

        this._projectList.expandSection(this._projectListPhotoBooks);
        this._onSectionChanged(this._projectList.getExpandedSection());
    },

    _populateProjectTabs: function() {
        this._projectListPhotoBooks.clear();
        if (this._userProjects != null)
            addProjectTabSections(this._userProjects);
    },

    _populateAlbumTabs: function() {
        this._albumsListUpload.clear();
        this._albumsListShared.clear();
        this._albumsListFriend.clear();

        if (this._userAlbums != null)
            addAlbumTabSections(this._userAlbums);

    },

    _onGotUserAlbums: function(result) {
        this._userAlbums = result;
        this._populateAlbumTabs();
        this._albumsList.expandSection(this._getDefaultSectionToDisplay());
        this._onSectionChanged(this._albumsList.getExpandedSection());
    },

    _getDefaultSectionToDisplay: function() {
        if (this._albumsListUpload.getLength() > 0) return this._albumsListUpload;
        else if (this._albumsListShared.getLength() > 0) return this._albumsListShared;
        else if (this._albumsListFriend.getLength() > 0) return this._albumsListFriend;
        else return this._albumsListUpload;
    },

    _getDataByType: function(array, type) {
        var result = [];

        if (array !== null) {
            for (var i = 0; i < array.length; i++) {
                if (array[i].Type == type) {
                    result.push(array[i]);
                }
            }
        }

        return result;
    },

    getProjectsByType: function(type) {
        return this._getDataByType(this._userProjects, type);
    },

    getAlbumsByType: function(type) {
        return this._getDataByType(this._userAlbums, type);
    },

    hasAlbums: function() {
        return this._userAlbums !== null;
    },

    getAlbumByID: function(id) {
        if (this._userAlbums === null) {
            return null;
        }

        for (var i = 0; i < this._userAlbums.length; i++) {
            if (this._userAlbums[i].ID == id) {
                return this._userAlbums[i];
            }
        }

        return null;
    },

    getDocuments: function() {
        return this._userDocuments;
    },

    getAlbumByID: function(id) {
        for (var i = 0; i < this._userAlbums.length; i++) {
            if (this._userAlbums[i].ID == id) {
                return this._userAlbums[i];
            }
        }
    },

    setManager: function(manager) {
        this._manager = manager;
    },

    getManager: function() {
        return this._manager;
    },

    setOnProjectChangedCallback: function(func) {
        this._onProjectChangedCallback = func;
    },

    _onProjectChanged: function(project) {
        if (this._onProjectChangedCallback !== null) {
            this._onProjectChangedCallback(project);
        }
    },

    setOnAlbumChangedCallback: function(func) {
        this._onAlbumChangedCallback = func;
    },

    _onAlbumChanged: function(album) {
        if (this._onAlbumChangedCallback !== null) {
            this._onAlbumChangedCallback(album);
        }
    },

    promptCreateNewAlbum: function(onSuccess) {
        PopupCreateAlbum.show();
    },

    _createNewAlbum: function(name, description) {
        if (name.length === 0 || description.length === 0) {
            var popParentNode = document.getElementById('CreateNewAlbum').parentNode;
            if (popParentNode != null) {
                popParentNode.style.zIndex = '9999';
            }
            msgBox.Show('Incomplete Information', SR.PleaseFillOutTheInformationRequired, [{ Button: 'Ok', Callback: showCreateAlbumPopup}]);

            return;
        }
        else {
            PopupCreateAlbum.hide();
        }

        this._albumsService.CreateAlbum(name, description, Function.createDelegate(this, this._onAlbumCreated), gotError);
    },

    _onAlbumCreated: function(result) {
        this._userAlbums.push(result);
        this._albumsListUpload.addFirstItem(result.Name, this._onAlbumChangedDelegate, result);

        if (this._albumsListUpload.expanded() === false) {
            this._albumsList.expandSection(this._albumsListUpload);
        }

        this._populateAlbumTabs();

        this._onSectionChanged(this._albumsListUpload);
    },

    removeAlbums: function(albums) {
        for (var i = 0; i < albums.length; i++) {
            Array.remove(this._userAlbums, albums[i]);
        }
        this._populateAlbumTabs();
    },

    removeDocuments: function(documents) {
        for (var i = 0; i < documents.length; i++) {
            Array.remove(this._userDocuments, documents[i]);
        }
        this._populateDocumentsTabs();
    },

    removeProject: function(project) {
        Array.remove(this._userProjects, project);
        this._populateProjectTabs();
    },

    addProject: function(project) {
        this._userProjects.push(project);
        this._populateProjectTabs();
        this._onSectionChanged(this._projectList.getExpandedSection());
    },
    addAlbums: function(albums) {
    if (albums != null) {
            for(var i = 0; i < albums.length; i++)
                this._userAlbums.push(albums[i]);
        }
        if (this._userAlbums != null)
            addAlbumTabSections(this._userAlbums);
            
        this._onSectionChanged(this._albumsList.getExpandedSection());
    },

    rePopulateAlbumTabs: function() {
        this._populateAlbumTabs();
    },

    rePopulateProjectTabs: function() {
        this._populateProjectTabs();
    }

};

//
// List
//

PhotoSite.TabsPanelList = function(parentDOMElement, liCollapsedStyle, liExpandedStyle) {
    this._sections = [];
    this._parentUlElement = document.createElement('ul');
    this._liCollapsedStyle = liCollapsedStyle;
    this._liExpandedStyle = liExpandedStyle;

    this._parentUlElement.setAttribute('style', 'list-style-type: none;'); //FB16647

    parentDOMElement.appendChild(this._parentUlElement);

    this._sectionClickDelegate = Function.createDelegate(this, this.expandSection);
};

PhotoSite.TabsPanelList.prototype = {
    _parentUlElement: null,
    _liCollapsedStyle: null,
    _liExpandedStyle: null,
    _sectionClickDelegate: null,
    _sections: null,

    getExpandedSection: function() {
        for (var i = 0; i < this._sections.length; i++) {
            if (this._sections[i].expanded()) {
                return this._sections[i];
            }
        }
        return null;
    },

    expandSection: function(section) {
        for (var i = 0; i < this._sections.length; i++) {
            if (this._sections[i] == section) {
                if (this._sections[i].expanded()) {
                    this._sections[i].collapse();
                }
                else {
                    this._sections[i].expand();
                }
            }
            else {
                this._sections[i].collapse();
            }
        }
    },

    addSection: function(ID, Text, onClickCallback) {
        return addSection(ID, Text, onClickCallback, '');

    },


    addSection: function(ID, Text, onClickCallback, ClassNumber) {
        var parent = this;
        var handler = function(section) {
            if (typeof (onClickCallback) !== 'undefined' && onClickCallback !== null) {
                onClickCallback(section);
            }
            parent._sectionClickDelegate(section);
        };
        //var section = new PhotoSite.TabsPanelListSection(this._parentUlElement, this._liCollapsedStyle, this._liExpandedStyle, ID, Text, handler);
        var section = new PhotoSite.TabsPanelListSection(this._parentUlElement, this._liCollapsedStyle, this._liExpandedStyle, ID, Text, handler, ClassNumber);
        this._sections.push(section);



        return section;
    }
};

PhotoSite.TabsPanelListSection = function(parentDOMElement, liCollapsedStyle, liExpandedStyle, ID, Text, onClickCallback, ClassNumber) {
    this._id = ID;
    this._liCollapsedStyle = 'sub_listing_collapsed'; //liCollapsedStyle;
    this._liExpandedStyle = 'sub_listing_expanded'; // liExpandedStyle;

    this._divElement = document.createElement('div');
    this._divElement.style.display = 'none';
    this._divElement.style.className = 'album_listing';


    this._headElement = document.createElement('div');
    this._headElement.innerHTML = '<a id=sectionTab' + ID + '>' + Text + '</a>';
    this._headElement.obj = this;
    this._headElement.onclick = function() { onClickCallback(this.obj); };
    this._headElement.style.cursor = 'pointer';     // FIXME: move to CSS
    this._headElement.className = 'album_listing' + ClassNumber;  //TODO: Temp fix Alex Wood

    this._liElement = document.createElement('li');
    this._liElement.appendChild(this._headElement);
    this._liElement.appendChild(this._divElement);
    this._liElement.className = this._liCollapsedStyle;

    parentDOMElement.appendChild(this._liElement);

};

PhotoSite.TabsPanelListSection.prototype = {
    _id: null,
    _domContent: null,
    _liElement: null,
    _divElement: null,
    _headElement: null,
    _liCollapsedStyle: null,
    _liExpandedStyle: null,
    _expanded: false,
    _length: 0,

    getLength: function() {
        return this._length;
    },

    getID: function() {
        return this._id;
    },

    _createItem: function(text, onClickCallback, context) {
        var p = document.createElement('p');
        var a = document.createElement('a');

        p.appendChild(a);
        a.id = 'add_photo_tab';
        a.innerHTML = text;
        a.href = '#';
        a.onclick = function() { if (onClickCallback) { onClickCallback(context); } return false; };

        return p;
    },

    addFirstItem: function(text, onClickCallback, context) {
        var item = this._createItem(text, onClickCallback, context);
        if (this._divElement.firstChild !== null) {
            this._divElement.insertBefore(item, this._divElement.firstChild);
        }
        else {
            this._divElement.appendChild(item);
        }
        this._length++;
    },

    clear: function() {
        while (this._divElement.firstChild) {
            this._divElement.removeChild(this._divElement.firstChild);
        }
        this._length = 0;
    },

    addItem: function(text, onClickCallback, context) {
        this._divElement.appendChild(this._createItem(text, onClickCallback, context));
        this._length++;
    },

    setTextIfNoItems: function(text) {
        if (this._divElement.firstChild === null) {
            this._divElement.appendChild(document.createTextNode(text));
        }
    },

    expanded: function() {
        return this._expanded;
    },

    expand: function() {
        this._liElement.className = this._liExpandedStyle;
        this._divElement.style.display = '';
        this._expanded = true;
    },

    collapse: function() {
        this._liElement.className = this._liCollapsedStyle;
        this._divElement.style.display = 'none';
        this._expanded = false;
    }
};

function showCreateAlbumPopup() {
    var popParentNode = document.getElementById('CreateNewAlbum').parentNode;
    if (popParentNode != null) {
        popParentNode.style.zIndex = '100000';
    }
}
