window.AdvancedSearchConstr = function() {};
window.AdvancedSearchConstr.prototype = {
	
	searchData: null,
	
	dateFormat: 'Y-m-d',
	
	authorAutocompleter : null,
	
	dateSelect : null,
	
	dateAdvancedPanel : null,
	
	dateFrom : null,
	
	dateTo : null,
	
	customDateFields: [],
	
	applied: false,
	
	init : function () {
		
		this.dateSelect = GUI.$('advSearchDate');
		if (!this.dateSelect) return null; // do not init this object if 'advSearchDate' is undefined 
		
		this.dateFormat = window.dateFormat.date_format;
		
		
	    this.dateAdvancedPanel = GUI.$('adv_search_cusom_dates');	    
	    
	    this.dateFrom = new GUI.Forms.DatePicker({
			format: this.dateFormat
	    });
	    this.dateFrom.render('adv_srch_date_from');
		this.dateFrom.on('change', function(dateFrom) {
			GUI.$('date_from').value = Number(dateFrom.getDate());
		});
	    
	    this.dateTo = new GUI.Forms.DatePicker({
			format: this.dateFormat
	    });
	    this.dateTo.render('adv_srch_date_to');
		this.dateTo.on('change', function(dateTo) {
			GUI.$('date_to').value = Number(dateTo.getDate());
		});
		
		this.dateSelect.on('change', bind(function() {
            if (this.dateSelect.value == 'custom') {
                this.dateAdvancedPanel.style.visibility = 'visible';
            } else {
                this.dateAdvancedPanel.style.visibility = 'hidden';
            }
        }, this));
	    
	    this.dateAdvancedPanel.style.visibility = 'hidden';

		try {
			var enableUserAutoComplateNum = 25;
			this.authorAutocomleter = new GUI.Forms.Combo({
                options: [],
				name: 'author',
                autoWidth : true,
                //listHeight : 8,
                minWidth: 300,
                autocomplete: account_users_num <= enableUserAutoComplateNum ? false : true,
                searchFields: ['login', 'fname', 'lname', 'email'],
                substituteValue: false,
//                dataUrl: (parseInt(account.users_num,10) <= (25+hiddenUsers)) ? false : base_url+'groups/searchUsers/',
                dataUrl: account_users_num <= enableUserAutoComplateNum ? false : base_href+'searchUsers/',
                showListOnClick: (parseInt(account_users_num,10) <= enableUserAutoComplateNum) ? true : false,
				defaultText: (parseInt(account_users_num,10) <= 25) ? false : i18n.lbl_any_author
            })
			
			this.authorAutocomleter.render('adv_search_author');
			
			if (account_users_num <= enableUserAutoComplateNum) {
				new Ajax.Request(base_href+"getUsersList", {
		            group: 'lManageEntries',
		            method: 'post',
		            onSuccess: (function(an) {
		                var response = an.responseText.evalJSON();
		                if (response) {
		                	response.unshift({'text': i18n.lbl_any_author, 'value': null, 'selected': true});
		                    this.authorAutocomleter.setOptions(response);
							if (this.searchData && this.searchData.author) {
	                            this.authorAutocomleter.setValue(this.searchData.author);
	                        }
		                }

		            }).bind(this)
		        });
			} else {
				if (this.searchData.author) {
					this.authorAutocomleter.setOptions([{
						value: this.searchData.author,
						text: this.searchData.author_name
					}]);
					this.authorAutocomleter.setValue(this.searchData.author);
				}
			}
			
		} catch (e) {
//			console.log(e);
		}
		
		// date custom fields
		
		for (var i = 0; i < this.customDateFields.length; i++) {
			
			var customField = this.customDateFields[i];
			
			customField.DateFrom = new GUI.Forms.DatePicker({
				format: this.dateFormat
			});
	        customField.DateFrom.render(customField.applyTo.from);
	        customField.DateFrom.on('change', (function(dateFrom) {
	            GUI.$(this.hiddenFields.from).value = Number(dateFrom.getDate());
	        }).bind(customField));	
			
			customField.DateTo = new GUI.Forms.DatePicker({
				format: this.dateFormat
			});
            customField.DateTo.render(customField.applyTo.to);
            customField.DateTo.on('change', (function(DateTo) {
                GUI.$(this.hiddenFields.to).value = Number(DateTo.getDate());
            }).bind(customField));
			
			customField.Select = GUI.$(customField.selectId);
			customField.Select.on('change', (function() {
				var value = this.Select.value;
				
				if (value == 'custom') {
	                GUI.$(this.advancedPanelId).style.visibility = 'visible';
	            } else {
	                GUI.$(this.advancedPanelId).style.visibility = 'hidden';
	            }
			}).bind(customField));
			
			customField.Select.value = customField.selectValue;
			try {
				GUI.Event.fire(customField.Select, 'change');
			} catch (e) {
//				console.log(e);
			}
		}
		
		// setup search form values
		
        if (this.searchData) {
			
            if (this.searchData.text) {
                GUI.$('advSearchSearchText').value = this.searchData.text;
            }
            if (this.searchData.searchIn) {
                GUI.$('advSearchSearchIn').value = this.searchData.searchIn;
            }
			
			// catIds
			if (this.searchData.catIds) {
				var catMultySelect = GUI.$('advSearchCatIds');
				for (var i = 0; i < this.searchData.catIds.length; i++) {
					for (var o = 0; o < catMultySelect.options.length; o++) {
						if (this.searchData.catIds[i] == catMultySelect.options[o].value) {
							catMultySelect.options[o].selected = true;
						}
					}
				}
            }
			if ((this.searchData.advSearchInSubCat || !this.searchData.searchText) && GUI.$('advSearchInSubCat')) {
				GUI.$('advSearchInSubCat').checked = true;
			}
			
			// advSearchDate
			if (this.searchData.dateFilter) {
				try {
	                GUI.$('advSearchDate').value = this.searchData.dateFilter;
					//date_from
					if (this.searchData.date_from) {
						var date = new Date();
						date.setTime(this.searchData.date_from);
					    this.dateFrom.setDate(date);
					}
					//date_to
					if (this.searchData.date_to) {
						var date = new Date();
                        date.setTime(this.searchData.date_to);
	                    this.dateTo.setDate(date);
	                }
				
	                GUI.Event.fire(GUI.$('advSearchDate'), 'change');
	            } catch (e) {
//	                console.log(e);
	            }
            }
			
			// custom fields
			if (this.searchData.customFields) {
                for (var i = 0; i < this.searchData.customFields.length; i++) {
					var cf_id    = this.searchData.customFields[i].cf_id;
					var cf_value = this.searchData.customFields[i].value;
					
					var field = GUI.$('cf_' + cf_id);
					try {
						if (field && field.tagName.toUpperCase()  != 'SELECT' && (typeof(cf_value)).toLowerCase() != 'object') { // for input and textarea
							field.value = cf_value;
						} else if (field && field.tagName.toUpperCase()  == 'SELECT' && (typeof(cf_value)).toLowerCase() != 'object') { // for select
							for (var o = 0; o < field.options.length; o++) {
								if (field.options[o].value == cf_value) {
									field.options[o].selected = true;
								}
							}
						} else if ((typeof(cf_value)).toLowerCase() == 'object') { // date or date and time fields
							for (var dcf = 0; dcf < this.customDateFields.length; dcf++) {
								if (this.customDateFields[dcf].selectId == 'cf_' + cf_id + '_date') {
										this.customDateFields[dcf].Select.value = cf_value.dateFilter; // select value
										if (cf_value.dateFilterFrom) {
											var date = new Date();
		                                    date.setTime(cf_value.dateFilterFrom);
											this.customDateFields[dcf].DateFrom.setDate(date);          // dateFrom picker value
										}
										if (cf_value.dateFilterTo) {
		                                    var date = new Date();
		                                    date.setTime(cf_value.dateFilterTo);
		                                    this.customDateFields[dcf].DateTo.setDate(date);            // dateTo picker value
		                                }
										GUI.Event.fire(this.customDateFields[dcf].Select, 'change');
									
								}
							}
						}
					} catch (e) {
//                        console.log(e);
                    }
				}
            }
			
        }
        else {
        	var advSearchInSubCat = GUI.$('advSearchInSubCat');
        	if (advSearchInSubCat)
        		advSearchInSubCat.checked = true;
		}
		
		//
        if ((!this.searchData || !this.searchData.catIds || this.searchData.catIds.length < 1) && GUI.$('advSearchCatIds')) {
			GUI.$('advSearchCatIds').options[0].selected = true;
		}
		
		this.applied = true;
		
		// check for the case when we need to hide advenced search form and apply additional logic to "advanced search" link
		if (window.layout && window.layout == 'SearchResults' && GUI.$('advSearchHolder')) {			
			if (this.searchData.dateFilter) {
				GUI.$('advSearchHolder').style.display = '';
			}
			
			if (GUI.$('advSearchLink')) {
				var a = GUI.$('advSearchLink');
				a.href = "#advSearchMainHolder";
				a.on('click', this.showAdvancedForm);
			}
		} else if (window.layout && window.layout != 'SearchResults' && GUI.$('advSearchHolder')) {
			GUI.$('advSearchHolder').style.display = '';
		}
		
		if (GUI.$('advSearchMainHolder')) {
			GUI.$('advSearchMainHolder').on('click', this.showAdvancedForm);
		}
	},
	
	showAdvancedForm: function() {
		if (GUI.$('advSearchHolder').style.display == 'none') {
			GUI.$('advSearchHolder').style.display = '';
		} else {
			GUI.$('advSearchHolder').style.display = 'none';
		}
	}
}

window.AdvancedSearch = new AdvancedSearchConstr();

GUI.onDOMReady(AdvancedSearch.init.bind(AdvancedSearch));
