var Search = {
	type 			: 'music',
	typeMusicAlt	: 'track',
	typePeopleAlt	: 'peoples',
	filterKey		: '',
	resultCount		: 0,
	filterCall		: {
		track		: false,
		artist		: false,
		radio		: false,
		indie		: false,
		klan		: false,
		peoples		: false,
		fans		: false
	},
	peopleKeys		: {
		filterKey		: '',
		limit			: 21,
		filterOnline	: false,
		filterSex		: '',
		filterCountry	: '',
		filterMinAge	: 18,
		filterMaxAge	: 99
	},
	fanKeys		: {
		type			: 'artist', 
		recordKey		: '',
		recordId		: '',
		limit			: 21,
		filterOnline	: false,
		filterSex		: '',
		filterCountry	: '',
		filterMinAge	: 18,
		filterMaxAge	: 99
	},
	Tabs			: {
		track		: null,
		artist		: null,
		radio		: null,
		indie		: null,
		klan		: null,
		peoples		: null,
		fans		: null
	},
	LastOverItem	: {
		artist		:null
	},
	EventHandlers 	: {},
	showResultCountOnTopTab: function() {
		if(typeof(parent.searchFrame)!='undefined') {
			parent.searchFrame.$('.top-tab .search .count').html('('+ Search.resultCount +')');
			parent.contentFrame.$('.top-tab .search .count').html('('+ Search.resultCount +')');
		}
	}
}
Search.EventHandlers = {
	// this is for music search
	onMusicSubmitSearch : function(defaultTab) {
		defaultTab = defaultTab || 'track';
		var filterKey = $.trim($('#music-search-box').val());
		if(filterKey==Search.filterKey) return;
		Search.filterKey = filterKey;
		if (filterKey.length < 1) {
			// do nothing
		} else {
			// Add loading
			$('#tab-content-'+Search.typeMusicAlt).html(
				Templates.Utilities.LoadingIndicator.html('search-results-loading', Dictionary.GENERAL.Loading, '')
			);
			
			// reset filterCalls
			Search.EventHandlers.clearFilterCalls();
			
			// show search content
			$('.search-content').fadeIn();

			// update filterKeys
			Search.Tabs['radio'].filterKey = Search.Tabs['klan'].filterKey = Search.Tabs['indie'].filterKey = Search.Tabs['artist'].filterKey = Search.Tabs['track'].filterKey = filterKey;
			
			// get all music tabs count
			Search.EventHandlers.getCount(defaultTab,true);
			
			// behave like the current tab clicked if no tab selected
			/**getCount already trigers tab click functions, no need to call)
			if (defaultTab == '') {
				Search.EventHandlers.onTabClick(Search.typeMusicAlt);
			} else {
				$('#tab-header-'+defaultTab+' .tab-link').click();
				Search.EventHandlers.onTabClick(defaultTab);
			}
			**/
		}
		
		return false;
	},
	onPeopleSubmitSearch : function () {
		
		if ($('#people-search-submit').hasClass('disabled')) {
			return false;
		}

		// reset filterCalls
		Search.EventHandlers.clearFilterCalls();
		
		// show search content
		$('.search-content').fadeIn();
		
		// update local keys
		var genderFilter = '';
		if ($('#people-search-gender-m').is(':checked') && !$('#people-search-gender-f').is(':checked'))
			genderFilter = 'male';
		if (!$('#people-search-gender-m').is(':checked') && $('#people-search-gender-f').is(':checked'))
			genderFilter = 'female';
		var filterKey;
		var filterId;
		if ($('#people-search-box').val() == $('#people-search-box').data('addDefaultValueBehaviour_empty_value')) {
			filterKey = '';
		} else {
			filterKey = $.trim($('#people-search-box').val());
			if(typeof($('#people-search-box').attr('artistId'))!='undefined') {
				filterId = $('#people-search-box').attr('artistId');
			}
		}
		// update filterKeys
		if(Search.typePeopleAlt=='peoples') {
			Search.peopleKeys.filterKey = filterKey;
			Search.peopleKeys.filterOnline = $('#people-search-online').is(':checked');
			Search.peopleKeys.filterSex = genderFilter;
			Search.peopleKeys.filterCountry = $('#user-country-select').val();
			Search.peopleKeys.filterMinAge = $('#people-search-age-from').val();
			Search.peopleKeys.filterMaxAge = $('#people-search-age-to').val();
			
			Search.Tabs['peoples'].filterKey = Search.peopleKeys.filterKey;
			Search.Tabs['peoples'].API_params = Search.peopleKeys;

			// behave like the current tab clicked
			Search.EventHandlers.onTabClick(Search.typePeopleAlt);
		} else {
			Search.fanKeys.recordKey = filterKey;
			Search.fanKeys.recordId = filterId;
			Search.fanKeys.filterOnline = $('#people-search-online').is(':checked');
			Search.fanKeys.filterSex = genderFilter;
			Search.fanKeys.filterCountry = $('#user-country-select').val();
			Search.fanKeys.filterMinAge = $('#people-search-age-from').val();
			Search.fanKeys.filterMaxAge = $('#people-search-age-to').val();
			if(Search.fanKeys.recordId>0) {
				Search.Tabs['fans'].API_params = Search.fanKeys;
				Search.EventHandlers.onTabClick(Search.typePeopleAlt);
			}
		}
		
		// get all people tabs count
		// TODO: After Fans added.
		//Search.EventHandlers.getCount(Search.typePeopleAlt);
		


		return false;
	},
	loadPeopleSearchFormElement: function (tab_name) {
		if(tab_name=='peoples') {
			if(Search.peopleKeys.filterKey!='') {
				$('#people-search-box').val(Search.peopleKeys.filterKey);
				$('#people-search-box').css({'color':$.fn.addDefaultValueBehaviour.defaults.focus_color});
			}
			if(Search.peopleKeys.filterOnline)
				$('#people-search-online').attr('checked', 'true');
			else
				$('#people-search-online').removeAttr('checked');
			if(Search.peopleKeys.filterSex=='male')
				$('#people-search-gender-m').attr('checked', 'true');
			else
				$('#people-search-gender-m').removeAttr('checked');
			if(Search.peopleKeys.filterSex=='female')
				$('#people-search-gender-f').attr('checked', 'true');
			else
				$('#people-search-gender-f').removeAttr('checked');
			$('#user-country-select').val(Search.peopleKeys.filterCountry);
			$('#people-search-age-from').val(Search.peopleKeys.filterMinAge);
			$('#people-search-age-to').val(Search.peopleKeys.filterMaxAge);
		} else {
			if(Search.fanKeys.recordKey!='') {
				$('#people-search-box').val(Search.fanKeys.recordKey);
				$('#people-search-box').css({'color':$.fn.addDefaultValueBehaviour.defaults.focus_color});
			}
			if(Search.fanKeys.filterOnline)
				$('#people-search-online').attr('checked', 'true');
			else
				$('#people-search-online').removeAttr('checked');
			if(Search.fanKeys.filterSex=='male')
				$('#people-search-gender-m').attr('checked', 'true');
			else
				$('#people-search-gender-m').removeAttr('checked');
			if(Search.fanKeys.filterSex=='female')
				$('#people-search-gender-f').attr('checked', 'true');
			else
				$('#people-search-gender-f').removeAttr('checked');
			$('#user-country-select').val(Search.fanKeys.filterCountry);
			$('#people-search-age-from').val(Search.fanKeys.filterMinAge);
			$('#people-search-age-to').val(Search.fanKeys.filterMaxAge);
		}
	},
	onTabClick : function (tab_name, fromTab) {
		if (Search.type == 'music') {
			// update current music tab
			Search.typeMusicAlt = tab_name;
		} else if (Search.type == 'people') {
			Search.typePeopleAlt = tab_name;
			if(typeof(fromTab)!='undefined' && fromTab) {
				if(Search.typePeopleAlt=='peoples') {
					$('#people-search-box').val(Dictionary.GENERAL.Username);
				} else {
					$('#people-search-box').val(Dictionary.GENERAL.Artist)				
				}
				$('#people-search-box').addDefaultValueBehaviour({'force': true});
				Search.EventHandlers.loadPeopleSearchFormElement(tab_name);
				if(Search.typePeopleAlt=='fans') {
					$('#people-search-box').unbind('keyup');
					$('#people-search-box').bind('keyup',function(e){ Search.EventHandlers.onSearchKeyUp(e, 'people'); });
					//people search autocomplete
					$('#people-search-box').autocomplete(Config.URL.API_WRAPPER, 
							{
								params: {id: '1', api: 'Artist', command:'list', params: {limit: 10}},
								onSelect: function(text, data) {
									$('#people-search-box').attr('value', text);
									$('#people-search-box').attr('artistId', data.id);
									Search.fanKeys.recordKey = text;
									Search.fanKeys.recordId = data.id;
									//Search.EventHandlers.onPeopleSubmitSearch();
									Search.EventHandlers.onTabClick('fans');
								}
							}
					);
				} else {
					$('#people-search-box').unbind('keyup');
					$('#people-search-box').bind('keyup',function(e){ Search.EventHandlers.onSearchKeyUp(e, 'people'); });
				}
			}
			// show the inner div which is hidden by default
			$('.people-results-inner').show();
		} 
		
		// to aviod ajax call for totalCount = 0
		// TODO: tab_name check will be removed when count added
		if (($('#tab-header-' + tab_name + ' .tab-link span').html() == "(0)") && tab_name != 'peoples' && tab_name != 'fans') {
			$('#tab-content-'+ tab_name).html('<div class="marvin-notfound">'+Dictionary.ERROR.NoEntry+'</div>');
		} else {
			// show the current tab
			if (!Search.filterCall[tab_name] && tab_name != 'peoples' && tab_name != 'fans') {
				Search.filterKey = $.trim($('#music-search-box').val());
				if(Search.filterKey.length>2) {
					Search.Tabs[tab_name].filterKey = Search.filterKey;
					Search.Tabs[tab_name].show();
					Search.filterCall[tab_name] = true;
				}
			} else if (tab_name == 'peoples' || tab_name == 'fans') {
				if(Search.EventHandlers.checkPeopleSearchTerm(false) && typeof(fromTab)=='undefined') {
					if(tab_name=='fans')
						Search.Tabs[tab_name].API_params = Search.fanKeys;
					Search.Tabs[tab_name].reset();
					Search.Tabs[tab_name].show();
				}
			}
		}
	},
	getCount : function (type_alt,isSearch)	{
		isSearch = isSearch || false;
		
		var parameters = [];
		if (Search.type == 'music') {
		
			parameters.push({
				id: 1,
				api: 'Song',
				command: 'list',
				params: {
					filterKey: $('#music-search-box').val(),
					limit: 1
				}
			});
			parameters.push({
				id: 2,
				api: 'Artist',
				command: 'list',
				params: {
					filterKey: $('#music-search-box').val(),
					limit: 1
				}
			});
			parameters.push({
				id: 3,
				api: 'Radio',
				command: 'list',
				params: {
					filterKey: $('#music-search-box').val(),
					limit: 1
				}
			});
			parameters.push({
				id: 4,
				api: 'Indie',
				command: 'list',
				params: {
					filterKey: $('#music-search-box').val(),
					limit: 1
				}
			});
			parameters.push({
				id: 5,
				api: 'Klan',
				command: 'list',
				params: {
					filterKey: $('#music-search-box').val(),
					limit: 1
				}
			});
		} else if (Search.type == 'people') {
			if(type_alt=='peoples') {
				var tempKeys = Search.peopleKeys;
				tempKeys.limit = 1;
				parameters.push({
					id: 1,
					api: 'User',
					command: 'list',
					params: tempKeys
				});
			} else {
				var tempKeys = Search.fanKeys;
				tempKeys.limit = 1;
				parameters.push({
					id: 1,
					api: 'User',
					command: 'listFavorite',
					params: tempKeys
				});
			}
		}
		var paramStr = JSONstring.make(parameters);
		paramStr = paramStr.substring(1,paramStr.length-1);
		$.postSK({
			data : {data: paramStr},
			onsuccess : function (data) {
				if (Search.type == 'music') {
					Search.resultCount = data['1'].totalCount + data['2'].totalCount + data['3'].totalCount
						+ data['4'].totalCount + data['5'].totalCount;
					$('#tab-header-track .tab-link span').html('('+data['1'].totalCount+')');
					$('#tab-header-artist .tab-link span').html('('+data['2'].totalCount+')');
					$('#tab-header-radio .tab-link span').html('('+data['3'].totalCount+')');
					$('#tab-header-indie .tab-link span').html('('+data['4'].totalCount+')');
					$('#tab-header-klan .tab-link span').html('('+data['5'].totalCount+')');
					Search.showResultCountOnTopTab();
				} else {
				}
				// TODO: remove search type when fans added
				if (isSearch && Search.type == 'music' && $('#tab-header-'+type_alt+' .tab-link span').html() == '(0)') {
					Search.EventHandlers.jumpToOtherTab(data);
				} else {
					$('#tab-header-'+type_alt+' .tab-link').click();
				}
			}
		});
	},
	jumpToOtherTab : function(data) {
		
		// get current tab's alt-tab names
		var tabsArr = $('#'+Search.type+'-results .tab');
		var c = 1;
		var currentTypeAlt = (Search.type == 'music') ? Search.typeMusicAlt : Search.typePeopleAlt;
		var found = false;
		
		$.each(tabsArr, function() {
			tab = $(this).attr('id').substr(11);
			if (!found && tab != currentTypeAlt && data[c].totalCount != 0) {				
				$('#tab-header-'+tab+' .tab-link').click();
				found = true;		
			}
			c++;
		});
	},
	onMenuChanged : function(t) {
		if (Search.type == t) return true;
		Search.type = t;
		if (t == 'people') {
			$('#people-search-box').val($('#music-search-box').val());
			$('.search-content').fadeOut({complete:function(){ 
				$('.search-bar').slideUp({ complete: function(){ 
						if (Search.peopleKeys.filterKey != '')
							$('.people-results-inner').show();
						$('#people-results').show();
						$('#music-results').hide(); 
						$('.search-content').fadeIn(); 
					}
				});
			}});	
			$('#tab-header-music').removeClass('selected');
			$('#tab-header-people').addClass('selected');
		} else if (t == 'music') {
			$('.search-content').fadeOut({complete:function(){ 
				$('.search-bar').slideDown({ complete: function(){
						$('#people-results').hide();
						$('#music-results').show(); 
						if ($('#music-search-box').val() != '')
							$('.search-content').fadeIn(); 
					}
				});
			}});
			$('#tab-header-people').removeClass('selected');
			$('#tab-header-music').addClass('selected');
		}
		return false;
	},
	onSearchKeyUp : function (e, type) {
		if (type == "music") {
		
			if ($('#music-search-box').val().length < 1) {
				$('#music-search-submit').animate({ opacity: 0.5 });
			}
			else {			
				$('#music-search-submit').animate({ opacity: 1 });
				var code = (e.keyCode ? e.keyCode : e.which);
				if(code == 13) { // Enter keycode
					$(this).blur();
					$('#music-search-submit').click();
					return false;
				}
			}
		} else {
			var code = (e.keyCode ? e.keyCode : e.which);
			if(code == 13) { // Enter keycode
				$(this).blur();
				Search.EventHandlers.checkPeopleSearchTerm();
				return false;
			}
		}
	},
	checkPeopleSearchTerm : function(callback) {
		var filterKey;
		var filterId;
		if ($('#people-search-box').val() == $('#people-search-box').data('addDefaultValueBehaviour_empty_value')) {
			filterKey = '';
		} else {
			filterKey = $.trim($('#people-search-box').val());
		}
		if(Search.typePeopleAlt=='fans') {
			filterId = $('#people-search-box').attr('artistId');
			if(typeof(filterId)=='undefined')
				filterId = 0;
		} else {
			filterId = 1;
		}
		var filterOnline = $('#people-search-online').is(':checked');
		var filterMale = $('#people-search-gender-m').is(':checked');
		var filterFemale = $('#people-search-gender-f').is(':checked');
		if ((filterKey != '' || filterOnline || filterMale || filterFemale) && filterId) {
			$('#people-search-submit').removeClass('disabled');
		} else {
			$('#people-search-submit').addClass('disabled');
		}
		
		if(typeof(callback)=='undefined') {
			callback = true;
		}
		if (callback && Search.type == 'people') {
			Search.EventHandlers.onPeopleSubmitSearch();
		} else {
			return !$('#people-search-submit').hasClass('disabled');
		}
	},
	clearFilterCalls : function() {
		Search.filterCall.artist = false;
		Search.filterCall.fans = false;
		Search.filterCall.peoples = false;
		Search.filterCall.radio = false;
		Search.filterCall.indie = false;
		Search.filterCall.klan = false;
		Search.filterCall.track = false;		
	}
}
// On DOM ready - Start
$(function() {

	$('#people-search-box').bind('keyup',function(e){ Search.EventHandlers.onSearchKeyUp(e, 'people'); });
	$('#music-search-box').bind('keyup',function(e){ Search.EventHandlers.onSearchKeyUp(e, 'music'); });
	$('#music-search-submit').animate({ opacity: 0.5 });
	
	// Bind form submit
	$('#search-music-form').bind('submit',function() { return false});
	$('#music-search-submit').bind('click',function() { Search.EventHandlers.onMusicSubmitSearch(Search.typeMusicAlt); });
	$('#search-people-form').bind('submit',function() { return false});
	$('#people-search-submit').bind('click',function() { Search.EventHandlers.onPeopleSubmitSearch(Search.typePeopleAlt); });
	
	// Add tab behaviour to all tabs
	$(".tab-container").addTabBehaviour({callback: function(tab) {Search.EventHandlers.onTabClick(tab, true)}});
	
	// Add menu behaviour
	$('#tab-header-people .tab-link').bind('click', function () { Search.EventHandlers.onMenuChanged('people'); });
	$('#tab-header-music .tab-link').bind('click', function () { Search.EventHandlers.onMenuChanged('music'); });
	
	// Close when a list item clicked
	$('.tab-content-container a:not(.icon)').livequery( function() { $(this).bind('click',Marvin.Search.close); });

	//people search form on change binds
	$('#people-search-online, #people-search-gender-m, #people-search-gender-f, #user-country-select, #people-search-age-from, #people-search-age-to').bind('change',Search.EventHandlers.checkPeopleSearchTerm);
	
	// Creating tab objects
	Search.Tabs.track = new marvinList({
		div_id:"tab-content-track",
		api:"Song.list", 
		apiParams:{ 
			limit: 25
		},
		template: Templates.Track.LineListItem,
		header: '<div class="line-list"><ul>',
		footer: '</ul></div>',
		show:false,
		search:true
	});
	Search.Tabs.artist = new marvinList({ 
		div_id:"tab-content-artist", 
		api:"Artist.list", 
		apiParams:{
			limit: 25
		},
		template: Templates.Artist.ListItem,
		header: '<div class="line-list"><ul class="with-image">',
		footer: '</ul></div>',
		show:false,
		search:true
	});
	Search.Tabs.radio = new marvinList({ 
		div_id:"tab-content-radio",
		api:"Radio.list", 
		apiParams:{
			limit: 5
		},
		template: Templates.Radio.ListItem,
		show:false,
		search:true
	});
	Search.Tabs.peoples = new marvinList({ 
		div_id:"tab-content-peoples",
		api:"User.list", 
		apiParams:{
			limit: 21
		},
		template: Templates.User.ListItem,
		templateParameters: {'lineBreakLimit': 7},
		show:false,
		search:true,
		onSuccess: function(data) {
			Search.resultCount = Search.Tabs.peoples.data.totalCount;
			$('#tab-header-peoples .tab-link span').html('('+Search.resultCount+')');
			Search.showResultCountOnTopTab();
		}
	});
	Search.Tabs.indie = new marvinList({ 
		div_id:"tab-content-indie", 
		api:"Indie.list", 
		apiParams:{
			limit: 25
		},
		template: Templates.Indie.ListItem,
		header: '<div class="line-list"><ul class="with-image">',
		footer: '</ul></div>',
		show:false,
		search:true
	});
	Search.Tabs.klan = new marvinList({ 
		div_id:"tab-content-klan",
		api:"Klan.list", 
		apiParams:{
			limit: 5,
			order: 'top'
		},
		template: Templates.Klan.ListItem,
		show:false,
		search:true
	});
	Search.Tabs.fans = new marvinList({ 
		div_id:"tab-content-fans",
		api:"User.listFavorite", 
		apiParams:{
			type: 'artist',
			limit: 21
		},
		template: Templates.User.ListItem,
		templateParameters: {'lineBreakLimit': 7},
		show:false,
		search:true,
		onSuccess: function(data) {
			Search.resultCount = Search.Tabs.fans.data.totalCount;
			$('#tab-header-fans .tab-link span').html('('+Search.resultCount+')');
			Search.showResultCountOnTopTab();
		}
	});
	
	
});
// On DOM ready - End