// handle advanced search form
var fShowLightBoxForm;
var fShowAdvancedSearchForm;
var fShowAdvancedSearchFormButton;
Ext.onReady(function(){
    fShowSearchForm();
    fShowChangeLightBoxForm();
});
//метод отображения формы поиска
//method of displaying search form
function fShowSearchForm()
{
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    var button = Ext.get('show_advanced_search_form_btn');
    var pGetExternalKeywords = false;
    var pGetExternalLocation = false;
    var pGetExternalCountry = false;
    var pGetExternalCity = false;
    var pGetExternalState = false;
    var pGetExternalDescription = false;
    var pGetExternalTitle = false;
    var pGetExternalPhotographerName = false;
    var pGetExternalByPhotographer = false;
    var pGetExternalByGallery = false;
    var pGetExternalDate = false;

    fShowAdvancedSearchForm = function(){

        var win_wait = Ext.MessageBox.show({
            title: TXT_LOADING,
            msg: TXT_LOADING,
            progressText: TXT_LOADING,
            waitConfig: {
                interval:100
            },
            wait: true,
            width:300,
            progress:true,
            closable:false,
            animEl: this
        });

        // handle main element for correct work on IE
        var tmpThis = this;

        Ext.BLANK_IMAGE_URL = 'library/extjs/i/default/s.gif';
        Ext.form.DateField.format = 'y-m-d';

        // getting all advanced search form data
        Ext.Ajax.request({
            method: 'POST',
            params: {
                advancedSearchForm: ''
            },
            url: exif_url,
            success: function(t) {
                if (t.responseText != "")
                {
                    setTimeout(function(){
                        win_wait.hide();
                    },3000);
                    fBuildAdvancedSearchForm(t);
                }
                else
                {
                    win_wait.hide();
                }
            },
            failure: function(){}
        });

        // advanced form builder
        var fBuildAdvancedSearchForm = function(t)
        {
            eval('var params = ' + t.responseText + ';');
            //alert(Ext.state.Manager.get('cookie_advancedSearchFormFilterActiveItemId'));
            /* create simple fields */
            var fCreateField = function(p, type)
            {
                var val = '';
                if (p == params.searchWordLocation)
                {
                    if (pGetExternalLocation != null && pGetExternalLocation != 'undefined' && pGetExternalLocation == true)
                    {
                        var val_location = fGetExternalLocationList('formLocation');
                        val = (val == '')? val_location : ((val_location == '')? val : val + ' ' + val_location);
                    }
                    if (pGetExternalCountry != null && pGetExternalCountry != 'undefined' && pGetExternalCountry == true)
                    {
                        var val_country = fGetExternalLocationList('formCountry');
                        val = (val == '')? val_country : ((val_country == '')? val : val + ' ' + val_country);
                    }
                    if (pGetExternalCity != null && pGetExternalCity != 'undefined' && pGetExternalCity == true)
                    {
                        var val_city = fGetExternalLocationList('formCity');
                        val = (val == '')? val_city : ((val_city == '')? val : val + ' ' + val_city);
                    }
                    if (pGetExternalState != null && pGetExternalState != 'undefined' && pGetExternalState == true)
                    {
                        var val_state = fGetExternalLocationList('formState');
                        val = (val == '')? val_state : ((val_state == '')? val : val + ' ' + val_state);
                    }
                }
                if (p == params.searchWordDescription)
                {
                    if (pGetExternalDescription != null && pGetExternalDescription != 'undefined' && pGetExternalDescription == true)
                    {
                        var val_description = fGetExternalLocationList('formDescription');
                        val = (val == '')? val_description : ((val_description == '')? val : val + ' ' + val_description);
                    }
                }
                if (p == params.searchWordTitle)
                {
                    if (pGetExternalTitle != null && pGetExternalTitle != 'undefined' && pGetExternalTitle == true)
                    {
                        var val_title = fGetExternalLocationList('formTitle');
                        val = (val == '')? val_title : ((val_title == '')? val : val + ' ' + val_title);
                    }
                }
                if (p == params.searchWordPhotographerName)
                {
                    if (pGetExternalPhotographerName != null && pGetExternalPhotographerName != 'undefined' && pGetExternalPhotographerName == true)
                    {
                        var val_photographername = fGetExternalLocationList('formPhotographerName');
                        val = (val == '')? val_photographername : ((val_photographername == '')? val : val + ' ' + val_photographername);
                    }
                }
                if (p == params.searchWordDate.from)
                {
                    if (pGetExternalDate != null && pGetExternalDate != 'undefined' && pGetExternalDate == true)
                    {
                        var val_date = fGetExternalLocationList('formDate');
                        val = (val == '')? val_date : ((val_date == '')? val : val + ' ' + val_date);
                    }
                }
                val = (val == '')? (p.value || '') : val;

                var tmpField = {
                    xtype: type,
                    fieldLabel: p.caption,
                    name: p.name,
                    value: val,
                    id: p.name + '_id',
                    anchor:'93%',
                    width: '100%',
                    alowBlank: true
                }
                if (type == 'datefield')
                {
                    tmpField.format = 'Y-m-d';
                }
                return tmpField;
            };

            /* create combobox fields */
            var fCreateComboBoxField = function(p)
            {
                var store_fields = new Array();
                var store_data = new Array();

                store_fields[0] = 'value';
                store_fields[1] = 'name';

                for(var i in p.values)
                {
                    var tmp = new Array();
                    tmp[0] = i;
                    tmp[1] = p.values[i];
                    store_data.push(tmp);
                }

                var store = new Ext.data.SimpleStore({
                    fields: store_fields,
                    data: store_data
                });

                var box = new Ext.form.ComboBox({
                    xtype:'combo',
                    allowBlank: false,
                    editable: false,
                    mode: 'local',
                    store: store,
                    autoHeight: true,
                    displayField:'name',
                    valueField:'value',
                    triggerAction: 'all',
                    selectOnFocus:true,
                    fieldLabel: p.caption,
                    hiddenName: p.name + '_id',
                    anchor:'100%',
                    width: '80%'
                });

                box.setValue(p.value);

                return box;
            };

            /* create search by photographer fields list */
            var fCreateSearchByPhotographerFieldsList = function(p)
            {
                var list = new Array();
                var checked = false;
                if (pGetExternalByPhotographer != null && pGetExternalByPhotographer != 'undefined' && pGetExternalByPhotographer == true)
                {
                    var photographer_id = fGetExternalByPhotographer('formPhotographerName');
                }

                for (var i in p)
                {
                    checked = p[i].value;
                    if (photographer_id != null && photographer_id != 'undefined')
                    {
                        checked = (photographer_id == p[i].id)? true : false;
                    }
                    var field = new Ext.form.Checkbox({
                        name: p[i].name,
                        id: p[i].name + '_id',
                        boxLabel: p[i].caption,
                        checked: checked
                    });

                    field.on('check', function() {
                        fHiglightAdvancedSearchFilter()
                        });
                    list.push(field);
                }

                return list;
            };

            /* create search by orientation fields list */
            var fCreateSearchByOrientationFieldsList = function(p)
            {
                var list = new Array();
                for (var id in p)
                {
                    var field = new Ext.form.Checkbox({
                        name: p[id].name,
                        id: p[id].name + '_id',
                        boxLabel: p[id].caption,
                        checked: p[id].value
                    });
                    field.on('check', function() {
                        fHiglightAdvancedSearchFilter()
                        });
                    list.push(field);
                }

                return list;
            };

            /* create search by photo category tree */
            var fCreateSearchByGalleryTree = function(p)
            {
                var checked = false;
                if (pGetExternalByGallery != null && pGetExternalByGallery != 'undefined' && pGetExternalByGallery == true)
                {
                    var gallery_id = fGetExternalByPhotographer('formGallery');
                }
                var fDrawTree = function(p, parent, root)
                {
                    for (var id in p)
                    {
                        checked = p[id].value;
                        if (gallery_id != null && gallery_id != 'undefined')
                        {
                            checked = (gallery_id == id)? true : false;
                        }
                        if (parent == p[id].parent)
                        {
                            var node = new Ext.tree.TreeNode(
                            {
                                text: p[id].caption,
                                allowDrag:false,
                                checked: checked,
                                id: p[id].name
                            }
                            );

                            if (checked == true)
                            {
                                var tmpfield = document.createElement('input');
                                tmpfield.setAttribute('name', p[id].name);
                                tmpfield.setAttribute('id', p[id].name + '_id');
                                tmpfield.setAttribute('value', 'on');
                                tmpfield.setAttribute('type', 'hidden');
                                document.getElementById('oBody').appendChild(tmpfield);

                                node.expanded = true;
                            }

                            node.on(
                                'checkchange',
                                function ()
                                {
                                    if (this.getUI().isChecked())
                                    {
                                        var tmpfield = document.getElementById(this.id + '_id');
                                        if (tmpfield == null || tmpfield == 'undefined')
                                        {
                                            var field = document.createElement('input');
                                        }
                                        else
                                        {
                                            var field = tmpfield;
                                        }
                                        field.setAttribute('name', this.id);
                                        field.setAttribute('id', this.id + '_id');
                                        field.setAttribute('value', 'on');
                                        field.setAttribute('type', 'hidden');
                                        if (tmpfield == null || tmpfield == 'undefined')
                                        {
                                            document.getElementById('oBody').appendChild(field);
                                        }
                                    }
                                    else
                                    {
                                        var tmpfield = document.getElementById(this.id + '_id');
                                        if (tmpfield != null && tmpfield != 'undefined')
                                        {
                                            document.getElementById('oBody').removeChild(tmpfield);
                                        }
                                    }
                                    fHiglightAdvancedSearchFilter();
                                }
                                );
                            fDrawTree(p, id, node);
                            root.appendChild(node);
                        }
                    }
                }

                var root = new Ext.tree.TreeNode({
                    allowDrag:false,
                    allowDrop:false
                });

                fDrawTree(p, '', root);

                return root;
            }

            /* clear advanced search form handler */
            var fClearAdvancedSearchForm = function()
            {
                var fClearField = function(name)
                {
                    var field = document.getElementById(name + '_id');
                    if (field != 'undefined' && field != null)
                    {
                        field.value = '';

                        /* checkboxes */
                        if (field.type == 'checkbox')
                        {
                            field.parentNode.parentNode.className = 'x-form-check-wrap';
                            field.checked = false;
                        }

                    }
                };
                for(var param_field in params)
                {
                    if (param_field == 'searchWord' ||
                        param_field == 'searchWordNOT' ||
                        param_field == 'searchWordTitle' ||
                        param_field == 'searchWordDescription' ||
                        //    					param_field == 'searchWordCountry' ||
                        //    					param_field == 'searchWordCity' ||
                        param_field == 'searchWordLocation' ||
                        param_field == 'searchWordKeywords' ||
                        param_field == 'searchWordPhotographerName' ||
                        param_field == 'searchWordExactMatch')
                        {
                        fClearField(params[param_field].name);
                    }
                    if (param_field == 'searchCondition')
                    {
                        pSearchCondition.setValue('and');
                    }
                    if (param_field == 'itemsPerPage')
                    {
                        pItemsPerPage.setValue('48');
                    }
                    if (param_field == 'sortBy')
                    {
                        pSortBy.setValue('uploaddate');
                    }
                    if (param_field == 'sortDirection')
                    {
                        pSortDirection.setValue('desc');
                    }
                    if (param_field == 'searchWordDate')
                    {
                        fClearField(params[param_field].from.name);
                        fClearField(params[param_field].to.name);
                    }
                    if (param_field == 'searchByGallery')
                    {
                        for(var gallery_id in params[param_field])
                        {
                            var tmpfield = document.getElementById(params[param_field][gallery_id].name + '_id');
                            if (tmpfield != null && tmpfield != 'undefined')
                            {
                                document.getElementById('oBody').removeChild(tmpfield);
                            }
                        }

                        var fClearTreeNodes = function(n)
                        {
                            for (var n_ in n.childNodes)
                            {
                                if (typeof(n.childNodes[n_]) == 'object')
                                {
                                    n.childNodes[n_].getUI().toggleCheck(false);
                                    fClearTreeNodes(n.childNodes[n_]);
                                }
                            }

                        };

                        fClearTreeNodes(pSearchByGalleryTree);
                    }
                    if (param_field == 'searchByPhotographer')
                    {
                        for(var photographer_id in params[param_field])
                        {
                            fClearField(params[param_field][photographer_id].name);
                        }
                    }
                    if (param_field == 'searchByOrientation')
                    {
                        for(var orientation in params[param_field])
                        {
                            fClearField(params[param_field][orientation].name);
                        }
                    }
                    if (param_field == 'searchByKeyword')
                    {
                        if(currentKeywordsDataStore.getCount() > 0)
                        {
                            currentKeywordsGridPanel.getStore().removeAll();
                        }
                    }
                }
            }

            /* higlight advanced search filter tabs */
            var fHiglightAdvancedSearchFilter = function(field_type)
            {
                var fCountCheckedItems = function(field_type)
                {
                    var cnt = 0;
                    for(var id in params[field_type])
                    {
                        var field = document.getElementById(params[field_type][id].name + '_id');
                        if (field != 'undefined' && field != null)
                        {
                            /* checkboxes */
                            if (field.type == 'checkbox')
                            {
                                if (field.checked)
                                {
                                    cnt++;
                                }
                            }
                            else
                            {
                                cnt++;
                            }
                        }
                    }
                    return cnt;
                };

                for (var i = 0; i <= filter.layout.container.items.items.length; i++)
                {
                    if (filter.layout.container.items.items[i] != null && filter.layout.container.items.items[i] != 'undefined')
                    {
                        if (filter.layout.container.items.items[i].id == 'searchByPhotographerTab')
                        {
                            var searchByPhotographer_cnt = fCountCheckedItems('searchByPhotographer');
                            if (searchByPhotographer_cnt > 0)
                            {
                                filter.layout.container.items.items[i].setTitle('<b>' + params.translations.TXT_FILTER_BY_PHOTOGRAPHER + ' (' + searchByPhotographer_cnt + ')' + '</b>');
                            }
                            else
                            {
                                filter.layout.container.items.items[i].setTitle(params.translations.TXT_FILTER_BY_PHOTOGRAPHER);
                            }
                        }
                        if (filter.layout.container.items.items[i].id == 'searchByOrientationTab')
                        {
                            var searchByOrientation_cnt = fCountCheckedItems('searchByOrientation');
                            if (searchByOrientation_cnt > 0)
                            {
                                filter.layout.container.items.items[i].setTitle('<b>' + params.translations.TXT_FILTER_BY_ORIENTATION + ' (' + searchByOrientation_cnt + ')' + '</b>');
                            }
                            else
                            {
                                filter.layout.container.items.items[i].setTitle(params.translations.TXT_FILTER_BY_ORIENTATION);
                            }
                        }
                        if (filter.layout.container.items.items[i].id == 'searchByGalleryTab')
                        {
                            var searchByGallery_cnt = fCountCheckedItems('searchByGallery');
                            if (searchByGallery_cnt > 0)
                            {
                                filter.layout.container.items.items[i].setTitle('<b>' + params.translations.TXT_FILTER_BY_GALLERY + ' (' + searchByGallery_cnt + ')' + '</b>');
                            }
                            else
                            {
                                filter.layout.container.items.items[i].setTitle(params.translations.TXT_FILTER_BY_GALLERY);
                            }
                        }
                        if (filter.layout.container.items.items[i].id == 'searchByKeywordTab')
                        {
                            var searchByKeyword_cnt = currentKeywordsDataStore.getCount();
                            if (searchByKeyword_cnt > 0)
                            {
                                filter.layout.container.items.items[i].setTitle('<b>' + params.translations.TXT_FILTER_BY_KEYWORD + ' (' + searchByKeyword_cnt + ')' + '</b>');
                            }
                            else
                            {
                                filter.layout.container.items.items[i].setTitle(params.translations.TXT_FILTER_BY_KEYWORD);
                            }
                        }
                    }
                }
            }

            /* submit advanced search form handler */
            var fSubmitAdvancedSearchForm = function()
            {
                var fCreateHiddenField = function(name)
                {
                    var field = document.getElementById(name + '_id');
                    if (field != 'undefined' && field != null)
                    {
                        var tmpfield = document.createElement('input');
                        tmpfield.setAttribute('name', name);
                        tmpfield.setAttribute('value', field.value);
                        tmpfield.setAttribute('type', 'hidden');

                        /* checkboxes */
                        if (field.type == 'checkbox')
                        {
                            if (field.checked)
                            {
                                form.appendChild(tmpfield);
                            }
                        }
                        else
                        {
                            form.appendChild(tmpfield);
                        }
                    }
                };

                var form = document.createElement('form');
                form.setAttribute('action', exif_url);
                form.setAttribute('id', 'advanced_search_form_id');
                form.setAttribute('method', 'get');

                for(var param_field in params)
                {
                    if (param_field == 'searchWord' ||
                        param_field == 'searchWordNOT' ||
                        param_field == 'searchWordTitle' ||
                        param_field == 'searchWordDescription' ||
                        //    					param_field == 'searchWordCountry' ||
                        //    					param_field == 'searchWordCity' ||
                        param_field == 'searchWordLocation' ||
                        param_field == 'searchWordKeywords' ||
                        param_field == 'searchWordPhotographerName' ||
                        param_field == 'searchCondition' ||
                        param_field == 'itemsPerPage' ||
                        param_field == 'sortBy' ||
                        param_field == 'sortDirection' ||
                        param_field == 'searchWordExactMatch')
                        {
                        fCreateHiddenField(params[param_field].name);
                    }
                    if (param_field == 'searchWordDate')
                    {
                        fCreateHiddenField(params[param_field].from.name);
                        fCreateHiddenField(params[param_field].to.name);
                    }
                    if (param_field == 'searchByGallery')
                    {
                        for(var gallery_id in params[param_field])
                        {
                            fCreateHiddenField(params[param_field][gallery_id].name);
                        }
                    }
                    if (param_field == 'searchByPhotographer')
                    {
                        for(var photographer_id in params[param_field])
                        {
                            fCreateHiddenField(params[param_field][photographer_id].name);
                        }
                    }
                    if (param_field == 'searchByOrientation')
                    {
                        for(var orientation in params[param_field])
                        {
                            fCreateHiddenField(params[param_field][orientation].name);
                        }
                    }
                    if (param_field == 'searchByKeyword')
                    {
                        if(currentKeywordsDataStore.getCount() > 0)
                        {
                            for (var i=0; i<currentKeywordsDataStore.getCount(); i++)
                            {
                                var tmpfield = document.createElement('input');
                                tmpfield.setAttribute('name', params[param_field].name + '[]');
                                tmpfield.setAttribute('value', currentKeywordsDataStore.getAt(i).data.value);
                                tmpfield.setAttribute('type', 'hidden');
                                form.appendChild(tmpfield);
                            }
                        }
                    }
                }
                document.getElementById('oBody').appendChild(form);
                document.getElementById('advanced_search_form_id').submit();
            };

            var keywordsSearchField = Ext.extend(Ext.form.TwinTriggerField, {
                initComponent : function(){
                    keywordsSearchField.superclass.initComponent.call(this);
                    this.on('specialkey', function(f, e){
                        if(e.getKey() == e.ENTER){
                            this.onTrigger2Click();
                        }
                    }, this);
                },

                validationEvent:false,
                validateOnBlur:false,
                trigger1Class:'x-form-clear-trigger',
                trigger2Class:'x-form-search-trigger',
                hideTrigger1:true,
                width:180,
                hasSearch : false,
                paramName : 'advancedSearchForm[keywordsQuery]',

                onTrigger1Click : function(){
                    if(this.hasSearch){
                        this.el.dom.value = '';
                        this.store.baseParams = this.store.baseParams || {};
                        this.store.baseParams[this.paramName] = '';
                        this.triggers[0].hide();
                        this.hasSearch = false;
                    }
                },

                onTrigger2Click : function(){
                    var v = this.getRawValue();
                    if(v.length < 1){
                        this.onTrigger1Click();
                        return;
                    }
                    this.store.baseParams = this.store.baseParams || {};
                    this.store.baseParams[this.paramName] = v;
                    this.store.reload();
                    this.hasSearch = true;
                    this.triggers[0].show();
                }
            });

            var availableKeywordsDataStore = new Ext.data.SimpleStore({
                fields: ['value', 'name'],
                //data: [[0, 0], [1, 1], [2, 2]]
                baseParams: {
                    advancedSearchForm: {
                        keywordsQuery: ''
                    }
                },
            url: exif_url
            });

        var fGetExternalKeywordsList = function ()
        {
            var result = new Array();
            var form = document.getElementById('formKeywords');
            if (form != null && form != 'undefined')
            {
                var elements_list = form.getElementsByTagName('input');
                for (var i = 0; i <= elements_list.length; i++)
                {
                    if (elements_list[i] != null && elements_list[i] != 'undefined' && elements_list[i].type != null && elements_list[i].type != 'undefined' && elements_list[i].type == 'checkbox' && elements_list[i].checked == true)
                    {
                        var tmpList = new Array();
                        tmpList[0] = elements_list[i].value;
                        tmpList[1] = document.getElementById(elements_list[i].id + '_link').innerHTML;
                        result.push(tmpList);
                    }
                }
            }

            return result;
        };

        var fGetExternalLocationList = function(n)
        {
            var result = '';
            var form = document.getElementById(n);
            if (form != null && form != 'undefined')
            {
                var elements_list = form.getElementsByTagName('input');
                for (var i = 0; i <= elements_list.length; i++)
                {
                    if (elements_list[i] != null && elements_list[i] != 'undefined' && elements_list[i].type != null && elements_list[i].type != 'undefined' && elements_list[i].type == 'checkbox' && elements_list[i].checked == true)
                    {
                        result = (result == '')? document.getElementById(elements_list[i].id + '_link').innerHTML : result + ' ' + document.getElementById(elements_list[i].id + '_link').innerHTML;
                    }
                }
            }
            return result;
        };

        var fGetExternalByPhotographer = function(n)
        {
            var result = '';
            var form = document.getElementById(n);
            if (form != null && form != 'undefined')
            {
                var elements_list = form.getElementsByTagName('input');
                for (var i = 0; i <= elements_list.length; i++)
                {
                    if (elements_list[i] != null && elements_list[i] != 'undefined' && elements_list[i].type != null && elements_list[i].type != 'undefined' && elements_list[i].type == 'checkbox' && elements_list[i].checked == true)
                    {
                        result = elements_list[i].value;
                    }
                }
            }
            return result;
        };

        if (pGetExternalKeywords != null && pGetExternalKeywords != 'undefined' && pGetExternalKeywords == true)
        {
            var currentKeywordsDataStore = new Ext.data.SimpleStore({
                fields: ['value', 'name'],
                data: fGetExternalKeywordsList()
            });
        }
        else
        {
            var currentKeywordsDataStore = new Ext.data.SimpleStore({
                fields: ['value', 'name'],
                data: params.searchByKeyword.values
            });
        };

        var pSearchByGalleryTree = fCreateSearchByGalleryTree(params.searchByGallery);

        // filter by photographer tab
        var filter_by_photographer = {
            title: params.translations.TXT_FILTER_BY_PHOTOGRAPHER,
            id: 'searchByPhotographerTab',
            border:false,
            layout: 'form',
            hideLabels: true,
            bodyStyle: 'width: auto; height: auto; padding: 5px;',
            fieldClass: '',
            itemCls: 'overflow_hidden',
            items: fCreateSearchByPhotographerFieldsList(params.searchByPhotographer)
        };

        // filter by orientation tab
        var filter_by_orientation = {
            title: params.translations.TXT_FILTER_BY_ORIENTATION,
            id: 'searchByOrientationTab',
            border:false,
            layout: 'form',
            hideLabels: true,
            bodyStyle: 'width: auto; height: auto; padding: 5px;',
            fieldClass: '',
            itemCls: 'overflow_hidden',
            items: fCreateSearchByOrientationFieldsList(params.searchByOrientation)
        };

        // filter by keyword tab
        var filter_by_keyword = {
            title: params.translations.TXT_FILTER_BY_KEYWORD,
            id: 'searchByKeywordTab',
            border:false,
            //			        bodyStyle: 'padding: 5px;',
            layout: 'border',
            autoScroll: false,
            tbar: [
            ' ',
            new keywordsSearchField({
                store: availableKeywordsDataStore,
                width: 340
            })
            ],
            items: [ availableKeywordsGridPanel = new Ext.grid.GridPanel(
            {
                region: 'west',
                xtype: 'grid',
                layout: 'fit',
                id: 'available_keywords_grid_id',
                store: availableKeywordsDataStore,
                columns: [
                {
                    header: 'Keywords',
                    fixed: true,
                    hidden: true
                },
                {
                    header: '',
                    fixed: true,
                    width: 1000
                }
                ],
                viewConfig: {
                    //forceFit:true,
                    enableRowBody:true,
                    showPreview:true
                },
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect:true
                }),
                bodyStyle: 'width: 100%',
                style: 'width: 50%',
                frame:true,
                iconCls:'icon-grid',
                tbar:[
                {
                    text:params.translations.TXT_MOVE,
                    handler: function()
                    {
                        var selectedRecord = availableKeywordsGridPanel.getSelectionModel().getSelected();
                        if (selectedRecord != null && selectedRecord != 'undefined')
                        {
                            var currKeyword = currentKeywordsGridPanel.getStore().query('name', selectedRecord.data.value);
                            if (currKeyword.getCount() > 0)
                            {
                                for (var i = 0; i < currKeyword.getCount(); i++)
                                {
                                    currentKeywordsGridPanel.getStore().remove(currKeyword.get(i));
                                }
                            }

                            currentKeywordsGridPanel.getStore().insert(0, selectedRecord);
                            availableKeywordsGridPanel.getStore().remove(selectedRecord);
                        }
                        fHiglightAdvancedSearchFilter();
                    }
                },
                {
                    text:params.translations.TXT_CLEAR,
                    handler: function()
                    {
                        availableKeywordsGridPanel.getStore().removeAll();
                        fHiglightAdvancedSearchFilter();
                    }
                }
                ]
            }),
            {
                region:'center',
                renderHidden: true,
                bodyStyle: 'width: 0%',
                style: 'width: 0%'
            },
            currentKeywordsGridPanel = new Ext.grid.GridPanel({
                region: 'east',
                xtype: 'grid',
                layout: 'fit',
                id: 'current_keywords_grid_id',
                store: currentKeywordsDataStore,
                columns: [
                {
                    header: 'Keywords',
                    fixed: true,
                    hidden: true
                },
                {
                    header: '',
                    fixed: true,
                    width: 1000
                }
                ],
                viewConfig: {
                    //forceFit:true,
                    enableRowBody:true,
                    showPreview:true
                },
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect:true
                }),
                bodyStyle: 'width: 100%',
                style: 'width: 50%',
                frame:true,
                iconCls:'icon-grid',
                tbar:[
                {
                    text:params.translations.TXT_MOVE,
                    handler: function()
                    {
                        var selectedRecord = currentKeywordsGridPanel.getSelectionModel().getSelected();
                        if (selectedRecord != null && selectedRecord != 'undefined')
                        {
                            var availKeyword = availableKeywordsGridPanel.getStore().query('name', selectedRecord.data.value);
                            if (availKeyword.getCount() > 0)
                            {
                                for (var i = 0; i < availKeyword.getCount(); i++)
                                {
                                    availableKeywordsGridPanel.getStore().remove(availKeyword.get(i));
                                }
                            }

                            availableKeywordsGridPanel.getStore().insert(0, selectedRecord);
                            currentKeywordsGridPanel.getStore().remove(selectedRecord);
                        }
                        fHiglightAdvancedSearchFilter();
                    }
                },
                {
                    text:params.translations.TXT_CLEAR,
                    handler: function()
                    {
                        currentKeywordsGridPanel.getStore().removeAll();
                        fHiglightAdvancedSearchFilter();
                    }
                }
                ]
            })
            ]
        };

        // filter by gallery tab
        var filter_by_gallery = {
            title: params.translations.TXT_FILTER_BY_GALLERY,
            id: 'searchByGalleryTab',
            //html:'',
            border:false,
            layout: 'fit',
            items: [
            {
                xtype: 'treepanel',
                rootVisible: false,
                bodyBorder: true,
                autoScroll: false,
                bodyStyle: 'width: 100%; height: 100%; overflow: auto;',
                root: pSearchByGalleryTree
            }
            ]
        };
        // filter panel
        var filter = new Ext.Panel({
            title: params.translations.TXT_FILTER,
            region: 'east',
            split: false,
            width: 350,
            //collapsible: true,
            margins:'0 0 0 0',
            cmargins:'0 0 0 0',
            layout: 'accordion',
            layoutConfig: {
            //animate:true
            //activeOnTop: true
            },
            defaults:{
                autoScroll:true
            },
            items: [
            filter_by_photographer,
            filter_by_orientation,
            filter_by_keyword,
            filter_by_gallery
            ]
        });
        //filter.on('staterestore', function () {alert('ddffgg')});
        var pSearchCondition = fCreateComboBoxField(params.searchCondition);
        var pItemsPerPage = fCreateComboBoxField(params.itemsPerPage);
        var pSortBy = fCreateComboBoxField(params.sortBy);
        var pSortDirection = fCreateComboBoxField(params.sortDirection);
        // getting main search form panel element
        var form = new Ext.FormPanel({
            labelAlign: 'left',
            bodyStyle:'padding:5px;',
            style: 'background-color: white;height: 500px;padding: 3px',
            region: 'center',
            layout: 'form',
            xtype: 'form',
            border: false,
            width: 650,
            method: 'GET',
            items: [
            //search_word,
            fCreateField(params.searchWord, 'textfield'),
            fCreateField(params.searchWordNOT, 'textfield'),
            //fCreateField(params.searchWordExactMatch, 'checkbox'),
            {
                xtype: 'fieldset',
                title: params.translations.TXT_SEARCH_CONDITIONS,
                autoHeight: true,
                autoWidth: true,
                items: [
                {
                    layout: 'column',
                    border: false,
                    autoHeight: true,
                    autoWidth: true,
                    items: [
                    {
                        labelAlign: 'top',
                        columnWidth:.5,
                        bodyStyle: 'padding: 0 10 0 0',
                        layout: 'form',
                        border: false,
                        items: [pSearchCondition]
                    },
                    {
                        labelAlign: 'top',
                        columnWidth:.5,
                        bodyStyle: 'padding: 0 10 0 0',
                        layout: 'form',
                        border: false,
                        items: [pItemsPerPage]
                    }

                    ]
                },
                {
                    layout: 'column',
                    border: false,
                    autoHeight: true,
                    autoWidth: true,
                    items: [
                    {
                        labelAlign: 'top',
                        columnWidth:.5,
                        bodyStyle: 'padding: 0 10 0 0',
                        layout: 'form',
                        border: false,
                        items: [pSortBy]
                    },
                    {
                        labelAlign: 'top',
                        columnWidth:.5,
                        bodyStyle: 'padding: 0 10 0 0',
                        layout: 'form',
                        border: false,
                        items: [pSortDirection]
                    }

                    ]
                },
                {
                    layout: 'column',
                    border: false,
                    width: '100%',
                    style: 'width: 100%',
                    items: [
                    {
                        labelAlign: 'left',
                        bodyStyle: 'padding: 0 10 0 0',
                        width: '100%',
                        layout: 'form',
                        border: false,
                        items: [
                        {
                            hideLabel: true,
                            xtype: 'checkbox',
                            name: params.searchWordExactMatch.name,
                            id: params.searchWordExactMatch.name + '_id',
                            boxLabel: params.searchWordExactMatch.caption,
                            checked: params.searchWordExactMatch.value
                        }]
                    }

                    ]
                }

                ]
            //checkboxToggle: true,
            //items: [search_word_date_from, search_word_date_to]
            },
            {
                xtype: 'fieldset',
                title: params.translations.TXT_PICTURE_INFO,
                autoHeight: true,
                autoWidth: true,
                //    		height: 200,
                items: [
                fCreateField(params.searchWordTitle, 'textfield'),
                fCreateField(params.searchWordDescription, 'textfield'),
                //					    	fCreateField(params.searchWordCountry, 'textfield'),
                //					    	fCreateField(params.searchWordCity, 'textfield'),
                fCreateField(params.searchWordLocation, 'textfield'),
                fCreateField(params.searchWordKeywords, 'textfield'),
                fCreateField(params.searchWordPhotographerName, 'textfield')
                ]
            },
            {
                xtype: 'fieldset',
                title: params.translations.TXT_PICTURE_DATE,
                autoHeight: true,
                autoWidth: true,
                style: 'text-align: center;',
                //			    		height: 200,
                items: [
                {
                    layout: 'column',
                    border: false,
                    width: '100%',
                    style: 'width: 100%;text-align: center;padding-bottom: 10px',
                    items: [
                    {
                        labelAlign: 'top',
                        columnWidth:.48,
                        layout: 'form',
                        border: false,
                        items: [fCreateField(params.searchWordDate.from, 'datefield')]
                    },
                    {
                        labelAlign: 'top',
                        columnWidth:.48,
                        layout: 'form',
                        border: false,
                        items: [fCreateField(params.searchWordDate.to, 'datefield')]
                    }
                    ]
                }
                ]
            //checkboxToggle: true,
            //items: [search_word_date_from, search_word_date_to]
            }
            ]
        });

        //tab2.render(document.body);

        var win = new Ext.Window({
            title: params.translations.TXT_ADVANCED_SEARCH,
            closable:true,
            width:800,
            height:560,
            //border:false,
            plain:true,
            layout: 'border',
            stateful: false,
            items: [form, filter],
            modal: true,
            resizable: false,
            buttons: [{
                text: params.translations.BTN_SEARCH,
                disabled:false,
                handler: function(){
                    Ext.state.Manager.set('cookie_advancedSearchFormFilterActiveItemId', filter.layout.activeItem.id);
                    fSubmitAdvancedSearchForm();
                }
            },{
                text: params.translations.BTN_CLEAR,
                disabled:false,
                handler: function(){
                    fClearAdvancedSearchForm();
                    fHiglightAdvancedSearchFilter();
                }
            },{
                text: params.translations.BTN_CLOSE,
                handler: function(){
                    win.close();
                }
            }]
        });
        win.on('hide', function()
        {
            var upload_tool = document.getElementById('upload_tool');
            if (upload_tool != 'undefined' && upload_tool != null)
            {
                upload_tool.style.visibility = 'visible';
            }
        }
        );

        setTimeout(
            function()
            {
                var upload_tool = document.getElementById('upload_tool');
                if (upload_tool != 'undefined' && upload_tool != null)
                {
                    upload_tool.style.visibility = 'hidden';
                }
                win.show(tmpThis);
                if (pGetExternalKeywords != null && pGetExternalKeywords != 'undefined' && pGetExternalKeywords == true)
                {
                    filter.layout.activeItem.collapse(0);
                    filter.layout.container.items.items[2].expand(0);
                }
                else
                {
                    for (var i = 0; i <= filter.layout.container.items.items.length; i++)
                    {
                        if (filter.layout.container.items.items[i] != null && filter.layout.container.items.items[i] != 'undefined')
                        {
                            if (filter.layout.container.items.items[i].id == Ext.state.Manager.get('cookie_advancedSearchFormFilterActiveItemId'))
                            {
                                filter.layout.activeItem.collapse(0);
                                filter.layout.container.items.items[i].expand(0);
                            }

                        }
                    }
                }
                fHiglightAdvancedSearchFilter();
                pGetExternalKeywords = false;
                pGetExternalLocation = false;
                pGetExternalCountry = false;
                pGetExternalCity = false;
                pGetExternalState = false;
                pGetExternalDescription = false;
                pGetExternalTitle = false;
                pGetExternalPhotographerName = false;
                pGetExternalByPhotographer = false;
                pGetExternalByGallery = false;
                pGetExternalDate = false;
            },
            2000
            );
    };
};
    if (button != null && button != 'undefined')
    {
        button.on('click', fShowAdvancedSearchForm);
        fShowAdvancedSearchFormButton = new Ext.Component({});
        fShowAdvancedSearchFormButton.addListener(
            'keywords_form_click',
            function()
            {
                pGetExternalKeywords = true;
                pGetExternalLocation = true;
                pGetExternalCountry = true;
                pGetExternalCity = true;
                pGetExternalState = true;
                pGetExternalDescription = true;
                pGetExternalTitle = true;
                pGetExternalPhotographerName = true;
                pGetExternalByPhotographer = true;
                pGetExternalByGallery = true;
                pGetExternalDate = true;
            }
            );
        fShowAdvancedSearchFormButton.on('click', fShowAdvancedSearchForm);
    }
}
//метод отображения формы лайтбокса
//method of displaying the form lightbox
function fShowChangeLightBoxForm()
{
    var LightBoxNameField;
    var buttons_send = Ext.query('.send_lightbox_class');
    var buttons_create = Ext.query('.create_lightbox_class');
    var buttons_edit = Ext.query('.edit_lightbox_class');
    var buttons_delete = Ext.query('.delete_lightbox_class');

    fShowLightBoxForm = function()
    {
        var action = this.id.match('create_lightbox_btn|edit_lightbox_btn|delete_lightbox_btn|send_lightbox_btn');
        var lightbox_id = (action=='edit_lightbox_btn' || action=='delete_lightbox_btn' || action == 'send_lightbox_btn')?this.id.substr(action.toString().length+1):'';
		var photo_id = (action)?this.id.substr(action.toString().length+1):'';
        // handle main element for correct work on IE
        var tmpThis = this;

		// show error on exceed lightbox limit
		if (action == 'create_lightbox_btn') {
            var lightbox_remains_el = document.getElementById('lightbox_remain');
            if (null != lightbox_remains_el && typeof(lightbox_remains_el) != 'undefined') {
                var lightbox_remains = parseInt(lightbox_remains_el.value);
                if (lightbox_remains < 1) {
                    alert(document.getElementById('lightbox_limit_caption').value);
                    return false;
                }
            }
		}

        Ext.Ajax.request({
            method: 'POST',
            params: {
                showLightBoxForm: action,
                lightboxId: lightbox_id
            },
            url: exif_url,
            success: function(t)
            {
                if (t.responseText != "")
                {                   
                    var response = t.responseText.split(',');
                    if(response[0] == "ERROR_LOGIN_BUYER")
                        window.location.href = response[1];
                    else
                        fBuildLightBoxForm(t,action);
                }
            },
            failure: function(){}
        });

        // create lightbox form builder
        var fBuildLightBoxForm = function(t,action)
        {
            eval('var params = ' + t.responseText + ';');
            var fCreateField = function(p, type)
            {
                var tmpField;
                if(type == 'textfield')
                {
                    tmpField = {
                        xtype: type,
                        fieldLabel: p.caption,
                        name: p.name,
                        value: p.value?p.value:'',
                        id: p.name + '_id',
                        anchor:'93%',
                        width: '100%',
                        allowBlank: false,
						blankText: 'This field is required',
						maxLength: 100
                    }
                    if(action == 'send_lightbox_btn')
                        tmpField['regex'] = /^([\w\-\'\-]+)(\.[\w-\'\-]+)*@([\w\-]+\.){1,5}([A-Za-z]){2,4}$/;
                }
                else if(type == 'label')
                {
                    tmpField = {
                        xtype: type,
                        text: params.translations.TXT_QUESTION_BEFORE_DELETE_LIGHTBOX
                    }
                }

                return tmpField;
            };

            LightBoxNameField = fCreateField(params.lightboxName, action!='delete_lightbox_btn'?'textfield':'label');

            // getting main search form panel element
            var form = new Ext.FormPanel({
                labelAlign: 'left',
				labelWidth: 40,
                bodyStyle:'padding:5px;',
                style: (action!='delete_lightbox_btn')?'background-color: white;height: 500px;padding: 3px;':'background-color: white;height: 500px;padding-top: 20px;',
                region: 'center',
                layout: 'form',
                xtype: 'form',
                border: false,
                width: 650,
                method: 'GET',
                items: [LightBoxNameField]
            });

            var win = new Ext.Window({
                title: (action == 'create_lightbox_btn')?params.translations.TXT_CREATE_NEW_LIGHTBOX:(action == 'edit_lightbox_btn')?params.translations.TXT_EDIT_LIGHTBOX:(action == 'send_lightbox_btn')?params.translations.TXT_SEND_BY_EMAIL_LIGHTBOX:params.translations.TXT_DELETE_LIGHTBOX,
                closable:true,
				width:280,
				height:150,
                plain:true,
                layout: 'border',
                stateful: false,
                items: [form],
                modal: true,
                resizable: false,
                buttons: [{
                    text: (action == 'create_lightbox_btn')?params.translations.BTN_CREATE:(action == 'edit_lightbox_btn')?params.translations.BTN_EDIT:(action == 'send_lightbox_btn')?params.translations.BTN_SEND:params.translations.BTN_DELETE,
                    disabled:false,
                    handler: function(){
                        fChangeLightBox(action,lightbox_id,win,params, photo_id)
                    }
                },
                {
                    text: params.translations.BTN_CLOSE,
                    handler: function(){
                        win.close();
                    }
                }]
            });

            setTimeout(
                function()
                {
                    var upload_tool = document.getElementById('upload_tool');
                    if (upload_tool != 'undefined' && upload_tool != null)
                    {
                        upload_tool.style.visibility = 'hidden';
                    }
                    win.show(tmpThis);

                },
                0
                );
        };

		// lightbox form callback
        var fChangeLightBox = function(action,lightbox_id,win,params,c_photo_id)
        {
            var lightbox_name = 'deleted_lightbox';
            if(action != 'delete_lightbox_btn' && action != 'send_lightbox_btn')
                lightbox_name = document.getElementsByName('lightbox_form[UBL_NAME]')[0].value;

            else if(action == 'send_lightbox_btn')
                lightbox_name = document.getElementsByName('lightbox_form[EMAIL]')[0].value;

			if (lightbox_name.toArray().size() > 100)
			{
				Ext.MessageBox.alert(TXT_WARNING, 'The name of the lightbox is too long. Please, limit your lightbox name to 100 characters.');
			}
            else if(lightbox_name != '' || action == 'delete_lightbox_btn' || action == 'send_lightbox_btn')
            {
                var error_email = false;
                if(action == 'send_lightbox_btn')
                {
                   var re = new RegExp(/^([\w\-\'\-]+)(\.[\w-\'\-]+)*@([\w\-]+\.){1,5}([A-Za-z]){2,4}$/);
                   var result = re.exec(lightbox_name);
                   if(result == null)
                   {
                        error_email = true;
                        Ext.MessageBox.alert(TXT_WARNING,MSG_FORM_IS_NOT_VALID);
                   }
                }
                if(error_email == false)
                {
                    Ext.Ajax.request({
						method: 'POST',
                        waitMsg: MSG_PLEASE_WAIT,
                        url: exif_url,
                        params: {
                            task: action,
                            lightboxName: lightbox_name,
                            lightboxId: lightbox_id
                        },
                        success: function(response)
                        {
                            var result=response.responseText;
                            if(result == 'ERROR_CHANGE_LIGHTBOX')
                            {
                                if(action == 'create_lightbox_btn')
                                    Ext.MessageBox.alert(TXT_WARNING,MSG_ERROR_CREATE_LIGHTBOX);
                                else if(action == 'edit_lightbox_btn')
                                    Ext.MessageBox.alert(TXT_WARNING,MSG_ERROR_MODIFY_LIGHTBOX);
                                else if(action == 'delete_lightbox_btn')
                                    Ext.MessageBox.alert(TXT_WARNING,MSG_ERROR_DELETE_LIGHTBOX);
                            }
                            else if(result == 'ERROR_LIMIT_LIGHTBOX')
                            {
                                Ext.MessageBox.alert(TXT_WARNING,MSG_ERROR_LIMIT);
                                win.close();
                            }
                            else if(result == 'ALREADY_CREATE_LIGHTBOX')
                                Ext.MessageBox.alert(TXT_NOTIFICATION,MSG_LIGHTBOX_ALREADY_CREATE);
                            else if(result == 'ERROR_SEND_LIGHTBOX')
                                Ext.MessageBox.alert(TXT_WARNING,MSG_ERROR_SEND_LIGHTBOX_BY_EMAIL);
                            else if(result == "COMPLETE_SEND_LIGHTBOX")
                            {
                                Ext.MessageBox.alert(TXT_NOTIFICATION,MSG_LIGHTBOX_SUCCESS_SEND);
                                win.close();
                            }
                            else
                            {
                                var lightbox = result.split(',');
                                var lightbox_id = lightbox[0];
                                var lightbox_name = lightbox[1];

                                if(action == 'create_lightbox_btn')
                                {
									// update remain count
                                    var remain = 0;
                                    var remain_el = document.getElementById('lightbox_remain');
                                    if (null != remain_el && typeof(remain_el) != 'undefined') {
                                        remain_el.value = parseInt(remain_el.value) - 1;
                                        remain = parseInt(remain_el.value);
                                    }
                                    var array_menu = document.getElementsByName('dropdown_menu_add_lightbox');
                                    if(array_menu.length != 0)
                                    {
                                        for(var i = 0; i < array_menu.length; i++)
                                        {
                                            var photo_id = array_menu[i].getAttribute('photo_id');
                                            var new_link = document.createElement("a");
                                            new_link.href = '#';
                                            var view = '';
                                            if(document.location.href.indexOf('item_id') != -1)
                                                view = '_view';
                                            new_link.setAttribute("onclick", "return fAddToLightBox(document.search_results" + view + ',' + lightbox_id + "," + photo_id + ")") ;
                                            new_link.setAttribute("style","background: url('i/menu_bg.gif') repeat scroll 0% 0% transparent;");
                                            new_link.setAttribute("class", "add_to_lightbox_class");
                                            new_link.innerHTML = lightbox_name + " (0)";
                                            // trigger add to lightbox event
											fAddToLightBox(
												(document.location.href.indexOf('item_id') != -1) ? document.search_results_view : document.search_results,
												lightbox_id, c_photo_id
											);   
 
                                            var create_button = document.getElementById('create_lightbox_btn_' + photo_id);                                                                                        
                                            array_menu[i].insertBefore(new_link,  create_button);
                                        }
                                        var count_items_all_menu = Ext.query('.add_to_lightbox_class').length;
                                        var count_lightbox = count_items_all_menu/array_menu.length;
                                        if(remain <= 0)
                                        {
                                            var mas_elements = document.getElementsByName('new_lightbox');
                                            for(var j = mas_elements.length-1; j >= 0; j--)
                                                mas_elements[j].parentNode.removeChild(mas_elements[j]);
                                        }
                                    }
                                    else
                                    {
                                        var list_lightbox = document.getElementsByName('lightbox_list')[0];
                                        var new_lightbox = "";
                                        if(list_lightbox != null && list_lightbox != 'undefined')
                                        {
                                            new_lightbox = document.createElement("div");
                                            new_lightbox.setAttribute("style","float: none;width:900px;");
                                            new_lightbox.setAttribute("class","tree");
                                            var link_lightbox = document.createElement("a");
                                            link_lightbox.setAttribute("style","height: 15px;");
                                            link_lightbox.setAttribute("name","lightbox_name_" + lightbox_id);
                                            link_lightbox.href = params.lightboxName.lang + "/login_buyers/lightbox/?lightbox_id=" + lightbox_id;
                                            link_lightbox.innerHTML = "<span style='clear:both; float:left;'>" + lightbox_name + "</span><span style='clear:right; float:left;' count_items='0'>&nbsp;(0)</span>";
                                            var img_delete_lightbox = document.createElement("input");
                                            img_delete_lightbox.setAttribute("type","image");
                                            img_delete_lightbox.setAttribute("onclick","javascript: return false;");
                                            img_delete_lightbox.title = BTN_DELETE;
                                            img_delete_lightbox.setAttribute("id","delete_lightbox_btn_" + lightbox_id);
                                            img_delete_lightbox.setAttribute("class","delete_lightbox_class");
                                            img_delete_lightbox.setAttribute("style","clear: right; display:block; float:right; padding-left:5px;");
                                            img_delete_lightbox.setAttribute("name",lightbox_name);
                                            img_delete_lightbox.setAttribute("src","i/delete.png");
                                            link_lightbox.appendChild(img_delete_lightbox);
                                            var img_edit_lightbox = document.createElement("input");
                                            img_edit_lightbox.setAttribute("type","image");
                                            img_edit_lightbox.setAttribute("onclick","javascript: return false;");
                                            img_edit_lightbox.title = BTN_EDIT;
                                            img_edit_lightbox.setAttribute("id","edit_lightbox_btn_" + lightbox_id);
                                            img_edit_lightbox.setAttribute("class","edit_lightbox_class");
                                            img_edit_lightbox.setAttribute("style","display:block; float:right;");
                                            img_edit_lightbox.setAttribute("name",lightbox_name);
                                            img_edit_lightbox.setAttribute("src","i/edit.png");
                                            link_lightbox.appendChild(img_edit_lightbox);                                            
                                            new_lightbox.appendChild(link_lightbox);
                                            list_lightbox.appendChild(new_lightbox);
                                            Ext.get("edit_lightbox_btn_" + lightbox_id).on('click', fShowLightBoxForm);
                                            Ext.get("delete_lightbox_btn_" + lightbox_id).on('click', fShowLightBoxForm);

											// update remain count
                                            var remain_el = document.getElementById('lightbox_remain');
											var remain = 0;
                                            if (null != remain_el && typeof(remain_el) != 'undefined') {
                                                remain = parseInt(remain_el.value);
                                                remain_el.value = remain - 1;
                                            }
                                        }
                                        var copy_menu_lightbox = document.getElementsByName('dropdown_menu_copy_lightbox')[0];
                                        if(copy_menu_lightbox != null && copy_menu_lightbox != 'undefined')
                                        {
                                            new_lightbox = document.createElement("a");
                                            new_lightbox.href = "#";
                                            new_lightbox.setAttribute("style","background: url('i/menu_bg.gif') repeat scroll 0% 0% transparent;");
                                            new_lightbox.setAttribute("onclick", "return fCopyOrMoveToLightBox(document.search_results," + lightbox_id + ",true);");
                                            new_lightbox.innerHTML = lightbox_name + " (0)";
                                            copy_menu_lightbox.setAttribute("style","display:block");
                                            copy_menu_lightbox.appendChild(new_lightbox);
                                        }
                                        var move_menu_lightbox = document.getElementsByName('dropdown_menu_move_lightbox')[0];
                                        if(copy_menu_lightbox != null && copy_menu_lightbox != 'undefined')
                                        {
                                            new_lightbox = document.createElement("a");
                                            new_lightbox.href = "#";
                                            new_lightbox.setAttribute("style","background: url('i/menu_bg.gif') repeat scroll 0% 0% transparent;");
                                            new_lightbox.setAttribute("onclick", "return fCopyOrMoveToLightBox(document.search_results," + lightbox_id + ",false);");
                                            new_lightbox.innerHTML = lightbox_name + " (0)";
                                            move_menu_lightbox.setAttribute("style","display:block");
                                            move_menu_lightbox.appendChild(new_lightbox);
                                        }

                                    }

                                    Ext.MessageBox.alert(
                                        TXT_NOTIFICATION,
                                        TXT_LIGHTBOX_SUCCESS_CREATE
                                        );
                                    win.close();

									// trigger a custom event to deliver to all subscribers
									jQuery('body').trigger('lightbox.created', [lightbox_id, lightbox_name]);

                                }
                                else if(action == 'edit_lightbox_btn')
                                {
									jQuery('#lightbox_name_' + lightbox_id).html(lightbox_name.escapeHTML());
                                    Ext.MessageBox.alert(
                                        TXT_NOTIFICATION,
                                        TXT_LIGHTBOX_SUCCESS_EDIT
                                        );
                                    win.close();

									// trigger a custom event to deliver to all subscribers
									jQuery('body').trigger('lightbox.edited', [lightbox_id, lightbox_name]);

                                }
                                else if(action == 'delete_lightbox_btn')
                                {
									// update remain count
                                    var remain_el = document.getElementById('lightbox_remain');
                                    var remain = 0;
								    if (null != remain_el && typeof(remain_el) != 'undefined') {
                                        remain = parseInt(remain_el.value);
                                        remain_el.value = remain + 1;
                                    }
                                    var delete_lightbox = jQuery('#lightbox_name_' + lightbox_id);
                                    var count_lightbox_items = delete_lightbox.find('span').eq(0).attr('count_items');
                                    var total_count_lightbox_items = document.getElementsByName('total_count_lightbox_items');
                                    for(var k = 0; k < total_count_lightbox_items.length; k++)
									{
										total_count_lightbox_items[k].innerHTML -= count_lightbox_items;
									}
									delete_lightbox.parent().remove();
									Ext.MessageBox.alert(
                                        TXT_NOTIFICATION,
                                        TXT_LIGHTBOX_SUCCESS_DELETE
                                        );
                                    win.close();

									// trigger a custom event to deliver to all subscribers
									jQuery('body').trigger('lightbox.deleted', [lightbox_id, lightbox_name]);
                                }
                            }
                        },
                        failure: function(response)
                        {
                            var result=response.responseText;
                            Ext.MessageBox.alert(TXT_ERROR,MSG_ERROR_CONNECT_TO_DATABASE);
                            win.close();
                        }
                    });
                }
            }
            else
            {
                Ext.MessageBox.alert(TXT_WARNING,MSG_FORM_IS_NOT_VALID);
            }
        };
    };
    fButtonSendClickHandler(buttons_send);
    fButtonCreateClickHandler(buttons_create);
    fButtonEditClickHandler(buttons_edit);
    fButtonDeleteClickHandler(buttons_delete);
}
//навешивание события на кнопки отправки
//attachment events to send button
function fButtonSendClickHandler(buttons_send)
{
    Ext.each(
        buttons_send,
        function(btn)
        {
            if(btn != null && btn != 'undefined')
            {
                Ext.get(btn.id).on('click', fShowLightBoxForm);
            }
        }
    );
}
//навешивание события на кнопки создания
//attachment events to create button
function fButtonCreateClickHandler(buttons_create)
{
    Ext.each(
        buttons_create,
        function(btn)
        {
            if(btn != null && btn != 'undefined')
            {
                Ext.get(btn.id).on('click', fShowLightBoxForm);
            }
        }
    );
}
//навешивание события на кнопки редактирования
//attachment events to edit button
function fButtonEditClickHandler(buttons_edit)
{
    Ext.each(
        buttons_edit,
        function(btn)
        {
            Ext.get(btn.id).on('click', fShowLightBoxForm);
        }
   );
}
//навешивание события на кнопки удаления
//attachment events to delete button
function fButtonDeleteClickHandler(buttons_delete)
{
    Ext.each(
        buttons_delete,
        function(btn)
        {
            Ext.get(btn.id).on('click', fShowLightBoxForm);
        }
    );
}
