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 = $('#faqContainer');

            // 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.faqTitles li, ul.faqTitles li div').click(FAQ.onChangeCategory);
            $('a#showNewDialog').click( FAQ.showNewSubcategoryDialog );

            var categoryId = FAQ.container.find('ul.faqTitles 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/dictionary/openIco.png')
				  .end()
				  .addClass('selected')
				  .find('div.expl').removeClass('hidden')
				  .end()
				  .find('div.right').removeClass('close').addClass('open')
				  					.find('span').text(AppData.lang.close)
				  					.end()
				  					.find('img').attr('src', 'appProxy/site/dictionary/windowClose.gif');

		//fix for ie6 browser
		if(jQuery.browser.msie && jQuery.browser.version == '6.0'){
			//remove backround-image:none added by png fix

			selectedLi.find('div.left *').not('span.title').remove();

			selectedLi.find('div.left').prepend($.create('img')
                        .attr('src','appProxy/site/dictionary/openIco.png')
                        .addClass('openCloseIcon'))
                        .css('marginTop', '15px')
                        .end()
                        .pngFix();
		}
	},

        onChangeCategory: function(event){
		
        if($(event.target).get().tagName != 'LI') var selectedLi = $(event.target).parent();
        else var selectedLi = $(event.target);
		
        FAQ.correctTabView(selectedLi);
		

                if ( !selectedLi.hasClass('selected') ) {
                    var categoryId = selectedLi.attr('id').split('_');
                    FAQ.categoryId = categoryId[1];
                    
                    var list = FAQ.container.find('ul.faqTitles');

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

                    //fix for ie6 browser
                    if(jQuery.browser.msie && jQuery.browser.version == '6.0'){
                            list.pngFix();

                            //remove filter added by png fix
                            previousSelected.get(0).runtimeStyle.filter = "";
                            //remove backround-image:none added by png fix
                            previousSelected.css('backgroundImage', '');
                    }

                    
                    FAQ.updateList();
                }

                return false;
	},

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

		var selectedLi = $(event.target).parents('li');
		selectedLi.find('img.openCloseIcon').attr('src', 'appProxy/site/dictionary/closeIco.png')
				  .end()
				  .removeClass('selected')
				  .find('div.expl').addClass('hidden')
				  .end()
				  .find('div.right').removeClass('open').addClass('close')
				  					.find('span').text(AppData.lang.open)
				  					.end()
				  					.find('img').attr('src', 'appProxy/site/dictionary/windowOpen.gif');

		//fix for ie6 browser
		if(jQuery.browser.msie && jQuery.browser.version == '6.0'){
			//remove backround-image:none added by png fix
			selectedLi.find('div.left *').not('span.title').remove();
			selectedLi.find('div.left').prepend($.create('img')
												 .attr('src','appProxy/site/dictionary/closeIco.png')
												 .addClass('openCloseIcon'))
												 .css('marginTop', '15px')
									   .end()
									   .pngFix();

		}
	},

        // 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.faqTitles li#catId_' + this.categoryId.value).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.faqTitles li#catId_' + that.categoryId.value).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/dictionary/'+state+'Ico.png" alt="" style="_margin-top:15px;" 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 += '<span>' + AppData.lang[langEntry] + '</span> <img src="appProxy/site/dictionary/window'+winIcon+'.gif" alt="" />'+
                 '</div>'+
                 '<div class="clear"></div>'+
                 '<div class="GEdit expl'+hiddenClass+'" id="home-infoEntryContent_' + id + '-global">'+content+'</div>';
        li.html( html );
        ul.prepend( 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')
                        });
        }
    },

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

                if (jQuery.browser.msie && jQuery.browser.version === '6.0') {
                    FAQ.container.find('ul.content').pngFix();
                }
            } // end if
        }); // end $.getJSON
    },
    
    correctTabView: function(selectedLi){
    	selectedLi.prevAll('li').children('div').css('marginLeft','15px');
    	selectedLi.nextAll('li').children('div').css('marginLeft','0px');
    	selectedLi.children('div').css('marginLeft', '0px');
    },
    
      /**
	*	every change of time value (Lightstreamer)
	*	we call to 'onUpdateTime' function
	*
	**/
	onUpdateTime: function() {
		
	}
}
$(document).ready(function() {
	FAQ.init();
});