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

        // @var int - keeps track of selected page in pagination
        currPage: 1,

        // @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,

        // @var int - query limits
        //
        limitStart: 0,
        limitEnd: 10,

        // @var string|null will refer to previous search result,
        //                  this is used in order to "know" when to reload pagination.
        //                  used in updateList() method
        prevSearchPhrase: null,

	init: function(){
        Dictionary.container = $('#dictionaryContainer');

        // Setup events
        Dictionary.container.find('div.left, div.right').toggle(Dictionary.onOpenEntry, Dictionary.onCloseEntry);
        Dictionary.container.find('a.deleteSubcategory').click( Dictionary.onDeleteSubcategory );
        Dictionary.container.find('a.renameSubcategory').click( Dictionary.showRenameSubcategoryDialog );
        $('a#showNewDialog').click( Dictionary.showNewSubcategoryDialog );
        $('form.search').submit( Dictionary.onSubmitSearch );
        Dictionary.paginationConfig(AppData.numberRecords, Dictionary.onPageChange);

	},
	
	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();
		}		 
	},
	
	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 === Dictionary.newDialog) {
                Dictionary.newDialog = $('#newDialog').submit(function(){Dictionary.onNewSubcategory.apply(Dictionary.newDialog[0]); return false});
                
                Dictionary.newDialog.dialog({
                            bgiframe: false,
                            resizable: false,
                            title: 'New Subcategory',
                            height:100,
                            modal: true,
                            overlay: {
                                    backgroundColor: '#000',
                                    opacity: 0.5
                            },
                            buttons: {
                                    OK: function() {
                                            Dictionary.onNewSubcategory.apply(Dictionary.newDialog[0]);
                                    },
                                    Cancel: function() {
                                            $(this).dialog('close');
                                    }
                            }
                    }).show();
            } else {
                Dictionary.newDialog.dialog('open');
            }

            Dictionary.newDialog.find('input[name=subcategoryName]').val('').focus();

            return false;
        },

        // Event: click ok on in the new subcategory dialog,
        //        'this' refers to the form within that dialog
        onNewSubcategory: function() {
            var that = this;
			
            $.getJSON(AppData.url + 'Dictionary/admin/newSubcategory/?lang=' + AppData.langId , $(this).serialize(), function( data ) {
                Dictionary.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 + 'Dictionary/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 === Dictionary.renameDialog) {
                Dictionary.renameDialog = $('#newDialog').clone().hide().appendTo(document.body);
                Dictionary.renameDialog.attr('id', 'renameDialog');
                Dictionary.renameDialog.submit( function() { Dictionary.onRenameSubcategory.apply(Dictionary.renameDialog[0]); return false; })

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

            var subcategoryId = $(this).parents('li').attr('id').split('_');
            var currName = $('li#subcatId_' + subcategoryId[1] + ' div.left span').html();

            Dictionary.renameDialog.find('input[name=subcategoryName]').val(currName).select().focus();
            Dictionary.renameDialog.find('input[name=subcategoryId]').val(subcategoryId[1]);

            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 + 'Dictionary/admin/renameSubcategory/?lang=' + AppData.langId , $(this).serialize(), function() {

                $('li#subcatId_' + that.subcategoryId.value + ' div.left span').html( that.subcategoryName.value );

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

            });
        },


    /**
     * Configures pagination
     *
     * @param int numberRecords - total number of elements
     * @param Function(Object e, int limitStart, int limitOffset, int pageNum) onChange -
     *             a callback which is triggered when navigating to a page
     */
    paginationConfig: function(numberRecords, onChange){
        //delete back and next button
        //because will created below
       Dictionary.container.find('#paginationContainer .back *,#paginationContainer .next *, #paginationContainer .pagination *').remove();

        jPagination.init ( { 	containers : { // HTML Elements - Wrapped in jQuery(!)
                                                        first : $('#paginationContainer .first'), back : $('#paginationContainer .back'), pagination : $('#paginationContainer .pagination'),
                                                        next : $('#paginationContainer .next'), last : $('#paginationContainer .last')
                                                },
                                                pagination : { // Integers
                                                        recordsNum : numberRecords, 
                                                        recordsPerPage : 10,
                                                        pagesToShow : 8,
                                                        defaultPage: Dictionary.currPage
                                                },
                                                callbacks : { // Callbacks
                                                onChange : onChange
                                                },
                                                strings : {		// Strings
                                                                first : '<<', 		// 'First page' string
                                                                back : '<',// 'Back page' 	string
                                                                next : '>',// 'Next page' 	string
                                                                last : '>>',		// 'Last page' 	string
                                                                seperator : ''		// Seperator 	string
                                                }

        });
    },

    /**
     * Callback used by jPagination which is triggered when navigating
     * to a different page.
     */
    onPageChange: function(e, limitStart, limitOffset, pageNum) {
        var searchPhrase = $('form.search').find('input[type=text]').val();

        Dictionary.limitStart = limitStart;
        Dictionary.limitOffset = limitOffset;

        Dictionary.container.find('ul').html('');
        Dictionary.updateList(  searchPhrase  );

        Dictionary.currPage = pageNum;
       
        return false;
    },

    /**
     * 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 = Dictionary.container.find('ul');
        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.append( li );
        
        if (state == 'close')  {
            li.find('div.left, div.right').toggle(Dictionary.onOpenEntry, Dictionary.onCloseEntry);
        } else {
            li.find('div.left, div.right').toggle(Dictionary.onCloseEntry, Dictionary.onOpenEntry);
        }
        

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

            GEdit.create( { container : li.find('.GEdit'),
                           toolbarContainer : $('#GEditToolbarContainer')
                        });
        }
    },

    /**
     * Fills up the <ul> with <li> containing entries, if searchPhrase is non-empty
     * then it uses it as search filter.
     *
     * @param string [optional:undefined] searchPhrase
     */
    updateList: function( searchPhrase ) {
      
        Dictionary.container.find('ul').html('');

        var url = AppData.url + 'Dictionary/getEntries/' + Dictionary.limitStart + '/' + Dictionary.limitEnd + '/?lang=' + AppData.langId;
        
        if (typeof searchPhrase !== 'undefined') {
            url += searchPhrase;
        }
        
        $.getJSON( url, function( data ) {
            $.each( data.entries, function() {
               if (null === this.content) {
                   this.content = AppData.lang.enterContent;
               }
               
               Dictionary.renderEntry(this.id, this.name, this.content, 'close');

               AppData.numberRecords = data.numberRecords;

               // Reset pagination only if previous search string and current search string were not empty
               if (typeof searchPhrase !== 'undefined' ) {
                   var resetPagination = true;

                   if (Dictionary.searchPhrase === Dictionary.prevSearchPhrase && Dictionary.prevSearchPhrase === '') {
                       resetPagination = false;
                   }

                   if (resetPagination) {
                        Dictionary.paginationConfig(AppData.numberRecords, Dictionary.onPageChange);
                   }
                   
               }
            }); // end $.each

            if (jQuery.browser.msie && jQuery.browser.version === '6.0') {
                Dictionary.container.find('ul').pngFix();
            }
        }); // end $.getJSON
    },

    // Event: submitting the search form by hitting <Enter> or clicking thje
    //        search button
    onSubmitSearch: function() {
        var searchPhrase = $('form.search').find('input[type=text]').val();

        // reset query offsets
        Dictionary.limitStart = 0;
        Dictionary.limitEnd = 10;

        Dictionary.updateList( searchPhrase );
        Dictionary.prevSearchPhrase = searchPhrase;

        return false;
    },
    /**
	*	every change of time value (Lightstreamer)
	*	we call to 'onUpdateTime' function
	*
	**/
	onUpdateTime: function() {
		
	}
   
}

$(document).ready(function() { 
	Dictionary.init();
});