function addAutocomplete(inputId, watermark, autocompleteUrl, callback, element_to_append_results) {
	/*var options = {
		'script':autocompleteUrl,
		'varname':"input",
		'json':true,						// Returned response type
		'shownoresults':false,				// If disable, display nothing if no results
		'noresults':"No Results",			// String displayed when no results
		'maxresults':8,					// Max num results displayed
		'cache':true,					// To enable cache
		'minchars':2,						// Start AJAX request with at leat 2 chars
		'timeout':100000,					// AutoHide in XX ms
		'callback': function(obj){
			callback(obj);
			$('#'+inputId).val( htmlspecialchars_decode(html_entity_decode(html_entity_decode( $('#'+inputId).val() ))));
		}, // Callback after click or selection
		'element_to_append_results':element_to_append_results,
		'showInfo':false
	};
	// Init autosuggest
	var as_json = new bsn.AutoSuggest(inputId, options);*/
	
	var options = {
		'source': autocompleteUrl,
		'minLength': 2,
		'appendTo': $(element_to_append_results),
		'select': function(event, ui) {
			//console.log(event, ui);
			callback(ui.item);
		}
	};
	
	$('#'+inputId).autocomplete(options);
	
	// Display a little watermak	
	$("#"+inputId).Watermark(watermark);
}

function beforeSubmitFunction(formData, jqForm, options) {
	if (typeof($('.autosuggest').attr('id')) != 'undefined') {
		return false;
	}
	
	var post = [];
	
	for (var i = 0; i < formData.length; i++) {
		if(formData[i].value == options['autocompleteWatermark']) {
			formData[i].value = '';
		} else {
			post[formData.name] = formData.value;
		}
	}

	formData = [];
	for (var onePostVar in post) {
		if (typeof onePostVar == 'undefined' || onePostVar == 'undefined') {
			continue;
		}
		formData.push({
			'name':onePostVar,
			'value':post[onePostVar]
		});
	}

	for (var filterCondition in skatic.tmp.filterConditions) {
		if (typeof filterCondition == 'undefined' || filterCondition == 'undefined') {
			continue;
		}

		formData.push({
			'name':filterCondition,
			'value':skatic.tmp.filterConditions[filterCondition]
		});
	}

	return true;
}

function getMusicPage(addFilter) {
	args = getFilterConditions(addFilter)
	var namedArgs = [];
	for (var arg in args) {
		namedArgs.push(args[arg].type+':'+args[arg].value);
	}
	if (namedArgs.length > 0) {
		var url = '/songs/index/'+namedArgs.join('/')+'/';
	} else {
		var url = '/songs/';
	}
	loadPage(url);
	
	return false;
}

function getFilterConditions(addFilter) {
	var args = {};
	var filtersCount = 0;
	
	for (var filterCondition in skatic.tmp.filterConditions) {
		if (typeof filterCondition == 'undefined' || filterCondition == 'undefined') {
			continue;
		}
		
		args[filterCondition] = skatic.tmp.filterConditions[filterCondition];
		filtersCount++;
	}
	
	if (typeof addFilter != 'undefined') {
		//console.info('addFilter', addFilter);
		if (typeof addFilter == 'string') {
			addFilter = JSON.parse(unescape(addFilter));
		}
		args[addFilter['type']] = addFilter;
		filtersCount++;
	}
//	console.warn(addFilter);
//	console.info(args);
//	console.error(filter);
	
	var filterHtml = new Array();
	
	var filterLabelsToHtml = {
		'artist': 'Artist',
		'album': 'Album',
		'song': 'Track',
		'genre': 'Genre',
		'tag': 'Tag'
	}
	
	if (filtersCount > 0) {
		filterHtml.push('<h3>Filter:</h3>');
		for (var filterCondition in args) {
			var removeLink = '<a href="#" onclick="removeFilterCondition(\''+filterCondition+'\');return false;"><img src="/img/del-small.gif" alt="Remove" title="Remove" /></a>&nbsp;</div>';
			filterHtml.push('<div class="filtertext"><span>'+filterLabelsToHtml[filterCondition]+'</span> {<span>'+args[filterCondition]['label']+'</span>}&nbsp;'+removeLink);
		}
	}
	
	$('#musicFilterDiv').html(filterHtml.join(''));
	
	skatic.tmp.filterConditions = args;
	
	return args;
}

var filterRemoveFlag = false;
function removeFilterCondition(filter) {
	if (typeof skatic.tmp.filterConditions[filter] == 'undefined') {
		return false;
	}
	
	delete skatic.tmp.filterConditions[filter];
	
	getFilterConditions();
	
	if (!filterRemoveFlag) {
		setTimeout(function(){
			getMusicPage();
			filterRemoveFlag = false;
		}, 1500);
	}
	filterRemoveFlag = true;
}

function addPopups(artistTh, albumTh, trackTh, genreTh, albumThDivWithLinks, albumThDivWithForm) {
	//console.log(artistTh, albumTh, trackTh, genreTh, albumThDivWithLinks, albumThDivWithForm);
	
	artistTh.myPopup({
		'popupElem':artistTh.find('div.rel'),
		'openTimeout':400,
		'timeout':1500,
		'bindClickToggle':false,
		'onFirstShow':function(s){
			$.requireScript(['/autocomplete/jquery.watermarkinput.js', '/js/jquery-ui-1.8.1.custom.min.js', '/js/jquery-ui-autocomplete.js'], function(){
				
				addAutocomplete(s.popupElem.find('input').attr('id'), 'Type artist name', '/users/autocompleteScreenName/', skatic.appliedAjaxMethods.musicFilterByArtist, s.popupElem[0]);
				$('#filterArtistsForm').ajaxForm({'beforeSubmit':beforeSubmitFunction, 'success':skatic.ajaxResponse, 'addReferer':true});

				albumThDivWithLinks.html('');
				
			}, {'parallel':false});
		}
	});
	
	albumTh.myPopup({
		'popupElem':albumTh.find('div.rel'),
		'timeout':1500,
		'bindClickToggle':false,
		'openTimeout':400,
		'onShow':function(s){
			var filterArtistsInputName = $('#filterArtistsInput').attr('name');
			
//			console.info(filterConditions, filterArtistsInputName, typeof filterConditions[filterArtistsInputName]);
			
			if (typeof skatic.tmp.filterConditions[filterArtistsInputName] != 'undefined') {
				
				if (albumThDivWithLinks.html().trim() != '') {
					return;
				}

				var artistScreenName = skatic.tmp.filterConditions[filterArtistsInputName].value;

				$.ajax({
					'url':'/albums/getJsonListForArtist/',
					'type':'POST',
					'data':{'artist':artistScreenName},
					'cache':true,
					'dataType':'json',
					'success':function(response){
						for (var i = 0; i < response.length; i++) {
							var link = document.createElement('a');
							$(link).attr('href', '#').html(response[i].Album.name).attr('rel', response[i].Album.slug).click(function(){
								getMusicPage({'type':'album','value':this.rel,'label':$(this).html()});
								return false;
							});
							albumThDivWithLinks.append(link);
						}

//						console.warn(albumThDivWithForm, albumThDivWithLinks);

						albumThDivWithForm.hide();
						albumThDivWithLinks.show();
					}
				});

			} else {

				if (albumThDivWithForm.is(':visible')) {
					return;	
				}

				$.requireScript(['/autocomplete/jquery.watermarkinput.js', '/js/jquery-ui-1.8.1.custom.min.js', '/js/jquery-ui-autocomplete.js'], function(){

					addAutocomplete(s.popupElem.find('input').attr('id'), 'Type album name', '/albums/autocomplete/', skatic.appliedAjaxMethods.musicFilterByAlbum, s.popupElem[0]);
					$('#filterAlbumsForm').ajaxForm({'beforeSubmit':beforeSubmitFunction, 'success':skatic.ajaxResponse, 'addReferer':true});
					albumThDivWithForm.show();
					albumThDivWithLinks.hide();

				}, {'parallel':false});
			}
		}
	});
	
	trackTh.myPopup({
		'popupElem':trackTh.find('div.rel'),
		'timeout':1500,
		'openTimeout':400,
		'bindClickToggle':false,
		'onFirstShow':function(s){
			$.requireScript(['/autocomplete/jquery.watermarkinput.js', '/js/jquery-ui-1.8.1.custom.min.js', '/js/jquery-ui-autocomplete.js'], function(){

				addAutocomplete(s.popupElem.find('input').attr('id'), 'Type track title', '/songs/autocomplete/', skatic.appliedAjaxMethods.musicFilterByTrack, s.popupElem[0]);
				$('#filterTracksForm').ajaxForm({'beforeSubmit':beforeSubmitFunction, 'success':skatic.ajaxResponse, 'addReferer':true});

			}, {'parallel':false});
		}
	});
	
	genreTh.myPopup({
		'popupElem':genreTh.find('div.rel'),
		'timeout':1500,
		'openTimeout':400,
		'bindClickToggle':false
	});
}

function closeAllPopups() {
	for (var id in skatic.myPopup) { //close other popups
		skatic.myPopup[id](); //call close function
	}
}

