// handle advanced search form
var fShowAdvancedSearchForm;
var fShowAdvancedSearchFormButton;
Ext.onReady(function(){

	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 id in p)
        		{
        			checked = p[id].value;
	    			if (photographer_id != null && photographer_id != 'undefined')
	    			{
	    				checked = (photographer_id == id)? true : false;
	    			}
        			var field = new Ext.form.Checkbox({
        				name: p[id].name,
        				id: p[id].name + '_id',
        				boxLabel: p[id].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);
    }
});

