var FAQ = {
        // @var JHTMLElement contains the entries list
	container: null,

        categoryId: '',

        // @var JHTMLElement - will refer to an instance of a new subcategory dialog
        newDialog: null,
        // @var JHTMLElement - will refer to an instance of a rename dialog
        renameDialog: null,

	init: function(){
            FAQ.container = $('div.mainContainer');

            // Setup events
            FAQ.container.find('div.left, div.right').toggle(FAQ.onOpenEntry, FAQ.onCloseEntry);
            FAQ.container.find('a.deleteSubcategory').click( FAQ.onDeleteSubcategory );
            FAQ.container.find('a.renameSubcategory').click( FAQ.showRenameSubcategoryDialog );
            FAQ.container.find('ul.assetsTitles li, ul.assetsTitles li div').click(FAQ.onChangeCategory);
            $('a#showNewDialog').click( FAQ.showNewSubcategoryDialog );

            var categoryId = FAQ.container.find('ul.assetsTitles li.selected').attr('id').split('_');
            FAQ.categoryId = categoryId[1];
	},

	onOpenEntry: function(event){
        if (event.target.nodeName === 'A') return;

var selectedLi = $(event.target).parents('li');

			selectedLi.find('img.openCloseIcon').attr('src', 'appProxy/site/education/arrow_expanded.gif')
					  .end()
					  .addClass('selected')
					  .find('div.expl').show('slow');
			},
			
			onCloseEntry: function(event){
			        if (event.target.nodeName === 'A') return;
			        
			var selectedLi = $(event.target).parents('li');
			selectedLi.find('img.openCloseIcon').attr('src', 'appProxy/site/education/arrow_collapsed.gif')
		  .end()
		  .removeClass('selected')
		  .find('div.expl').hide('fast')
		  
},

        onChangeCategory: function(event){
		
        if($(event.target).get().tagName != 'LI') var selectedLi = $(event.target).parent();
        else var selectedLi = $(event.target);
		
                if ( !selectedLi.hasClass('selected') ) {
                    var categoryId = selectedLi.attr('id').split('_');
                    FAQ.categoryId = categoryId[1];
                    
                    var list = FAQ.container.find('ul.assetsTitles');

                    var previousSelected = list.find('li.selected');
                    previousSelected.removeClass('selected');
                    selectedLi.addClass('selected')

                    FAQ.updateList();
                }

                return false;
	},


        // Event: click the New button in the title bar, when logged in as admin,
        // allows u to come up with new subcategories
        showNewSubcategoryDialog: function() {
            if (null === FAQ.newDialog) {
                FAQ.newDialog = $('#newDialog').submit(function(){FAQ.onNewSubcategory.apply(FAQ.newDialog[0]); return false});

                FAQ.newDialog.dialog({
                            bgiframe: false,
                            resizable: false,
                            title: 'New Subcategory',
                            height:140,
                            modal: true,
                            overlay: {
                                    backgroundColor: '#000',
                                    opacity: 0.5
                            },
                            buttons: {
                                    OK: function() {
                                            FAQ.onNewSubcategory.apply(FAQ.newDialog[0]);
                                    },
                                    Cancel: function() {
                                            $(this).dialog('close');
                                    }
                            }
                    }).show();
            } else {
                FAQ.newDialog.dialog('open');
            }

            // set default values - subcategory name and category id
            FAQ.newDialog.find('input[name=subcategoryName]').val('').focus();

            FAQ.newDialog.find('select').val(FAQ.categoryId);
            
            return false;
        },

        // Event: click ok on in the new subcategory dialog,
        //        'this' refers to the form within that dialog
        onNewSubcategory: function() {
            var that = this;
            FAQ.container.find('ul.assetsTitles li#catId_' + this.categoryId.value +' div').click();
            
            $.getJSON(AppData.url + 'AssetIndex/admin/newSubcategory/?lang=' + AppData.langId , $(this).serialize(), function( data ) {

                FAQ.renderEntry(data.id, that.subcategoryName.value, AppData.lang.enterContent, 'open');

                $(that).dialog('close');

            });
        },

        // Event: click on 'delete' on a subcategory's title
        onDeleteSubcategory: function() {
            if ( confirm('Are you sure you want to remove this subcategory?') ) {
                var that = this;
                var subcategoryId = $(this).parents('li').attr('id').split('_');
                subcategoryId = subcategoryId[1];

                $.get(AppData.url + 'AssetIndex/admin/deleteSubcategory/?lang=' + AppData.langId , {subcategoryId: subcategoryId}, function() {
                    $(that).parents('li').remove();
                });
            }

            return false;
        },

        // Event: click on rename anchor in a subcategory title
        showRenameSubcategoryDialog: function() {

            if (null === FAQ.renameDialog) {
                FAQ.renameDialog = $('#newDialog').clone().hide().appendTo(document.body);
                FAQ.renameDialog.attr('id', 'renameDialog');
                FAQ.renameDialog.submit( function() { FAQ.onRenameSubcategory.apply(FAQ.renameDialog[0]); return false; })


                FAQ.renameDialog.dialog({
                            bgiframe: false,
                            resizable: false,
                            title: 'Rename Subcategory',
                            height:140,
                            modal: true,
                            overlay: {
                                    backgroundColor: '#000',
                                    opacity: 0.5
                            },
                            buttons: {
                                    OK: function() {
                                            FAQ.onRenameSubcategory.apply(FAQ.renameDialog[0]);
                                    },
                                    Cancel: function() {
                                            $(this).dialog('close');
                                    }
                            }
                    }).show();
            } else {
                FAQ.renameDialog.dialog('open');
            }

            var subcategoryId = $(this).parents('li').attr('id').split('_');

            var currName = $('li#subcatId_' + subcategoryId[1] + ' div.left span').html();
            FAQ.renameDialog.find('input[name=subcategoryName]').val(currName).select().focus();
            FAQ.renameDialog.find('input[name=subcategoryId]').val(subcategoryId[1]);
            FAQ.renameDialog.find('select').val(FAQ.categoryId);

            return false;
        },

        // Event: click ok on in the rename subcategory dialog,
        //        'this' refers to the form within that dialog
        onRenameSubcategory: function () {
            var that = this;

            $.get(AppData.url + 'AssetIndex/admin/renameSubcategory/?lang=' + AppData.langId , $(this).serialize(), function() {
                $('li#subcatId_' + that.subcategoryId.value + ' div.left span').html( that.subcategoryName.value );
                FAQ.container.find('ul.assetsTitles li#catId_' + that.categoryId.value + ' div').click();

                $(that).dialog('close');
            });
        },


        /**
         * Renders an expandable <li> with contents <div> (and as GEdit if admin)
         *
         * id - id of entry
         * name - name of entry
         * content - gedit content
         * state - 'close' for closed entries, 'open' for open entries
         */
        renderEntry: function(id, name, content, state) {

            var ul = FAQ.container.find('ul.content');
            var li = $('<li/>').attr('id', 'subcatId_' + id).addClass('first');
            
            
            var langEntry = 'close';
            var winIcon   = 'Close';
            var hiddenClass = '';

            if (state == 'close') {
                langEntry = 'open';
                winIcon   = 'Open';
                hiddenClass = ' hidden ';
            } else {
                li.addClass('selected');
                
            }

            var html = '<div class="left">'+
                        '<img src="appProxy/site/education/arrow_collapsed.gif" class="openCloseIcon" />'+
                                        '<span class="title">'+
                                        name +
                        '</span>'+
                        '</div>'+
                        '<div class="right '+state+'">';
                    
                     if (AppData.isAdmin) {
                            html += '<a href="#" class="renameSubcategory">'+ AppData.lang['rename'] +'</a> ' +
                            '<a href="#" class="deleteSubcategory">' + AppData.lang['delete'] + '</a> ';
                     }

                     html += '</div>' + '<div class="clear"></div>'+
                     '<div class="GEdit expl'+hiddenClass+'" id="home-infoEntryContent_' + id + '-global">'+content+'</div>';
            li.html( html );
            ul.append( li );
            
            if (state == 'close')  {
                li.find('div.left, div.right').toggle(FAQ.onOpenEntry, FAQ.onCloseEntry);
            } else {
                li.find('div.left, div.right').toggle(FAQ.onCloseEntry, FAQ.onOpenEntry);
            }
            

            if (AppData.isAdmin) {
                li.find('a.deleteSubcategory').click( FAQ.onDeleteSubcategory );
                li.find('a.renameSubcategory').click( FAQ.showRenameSubcategoryDialog );
                

                GEdit.create( { container : li.find('.GEdit'),
                               toolbarContainer : $('#GEditToolbarContainer')
                            });
            }
        },
/*   '<div class="GEdit expl'+hiddenClass+'" id="home-infoEntryContent_' + id + '-global">'+content+'</div>'; */
    /**
     * Fills up the <ul> with <li> containing entries according to selected
     * category
     */
    updateList: function( ) {

        FAQ.container.find('ul.content').html('');
        var url = AppData.url + 'AssetIndex/getEntries/' + FAQ.categoryId + '?lang=' + AppData.langId;

        $.getJSON( url, function( data ) {
            if ( parseInt(data.numberRecords) )
            {
                $.each( data.entries, function() {
                   if (null === this.content) {
                       this.content = AppData.lang.enterContent;
                   }

                   FAQ.renderEntry(this.id, this.name, this.content, 'close');

                }); // end $.each

            } // end if
        }); // end $.getJSON
    },
    
      /**
	*	every change of time value (Lightstreamer)
	*	we call to 'onUpdateTime' function
	*
	**/
	onUpdateTime: function() {
		
	}
}
$(document).ready(function() {
	FAQ.init();
});
