var myDropDown, mySuggestion, myAjax;
jQuery(window).bind("load", function() {
	jmplayer.init();
	
	$("#advance_btn").click(function() {
		$("#advance_options").slideToggle("slow"); 
		if ($(this).hasClass("up")) {
			$(this).addClass("down").removeClass("up");
			document.cookie = 'op=bas';
		} else {
			$(this).addClass("up").removeClass("down");
			document.cookie = 'op=adv';
		}
	 });

	$(".linkCategory input").bind("click", function(e) {
		toggleCategory($(this).val());
	});
	$(".linkCategory label").bind("click", function(e) {
		var id = "#" + $(this).attr("for");
		toggleCategory($(id).val());
		// prevent triggering click event on the radio button
		e.preventDefault();
		// check the radio button manually
		$(id).attr("checked", "checked");
	});
	
	mySuggestion = new AjaxSuggestion({
		timeoutInterval: 500,
		callback: onSuggest
	});

	myDropDown = new AjaxDropDown({
		source: 'ajaxDropDownMenu',
		anchor: 'ajaxDropDownAnchor',
		offset: {
			top: $("#keyword").height() + 3,
			left: 0
		},
		inputElem: 'keyword',
		onSuggest: function(text) {mySuggestion.onSuggest(text);},
		onSelect: function(text) {$("#search_form").trigger("submit");}
	});
	
	$("#search_form").bind("submit", function(e) {
		if (myAjax != null) {
			myAjax.abort();
		}
	});
	
	$("#selSortBy").bind("change", function(e) {
		$("#txtSortBy").val($("#selSortBy").val());
		$("#search_form").submit();
	});
	
	$("#historySelSortBy").bind("change", function(e) {
		$("#historyTxtSortBy").val($("#historySelSortBy").val());
		$("#historyForm").submit();
	});
});

function onSuggest(txt) {
	var searchBy = $("#search_by").val();
	var ajaxType;
	if (searchBy == 1)
		ajaxType = "title";
	else if (searchBy == 2)
		ajaxType = "artist";
	else
		ajaxType = "track";
	if (myAjax != null) {
		myAjax.abort();
	}
	myAjax = $.get("ajax/search.asp", { ajax: ajaxType, query: txt },
		function(data) {
			responseObject = eval('(' + data + ')');
			var sug = new Array();
			for (var i = 0; i < responseObject.text.length; i++) {
				sug.push(responseObject.text[i]);
			}
			myDropDown.generateSuggestions(sug);
		}
	);
}

function toggleCategory(val) {
	var i, j, lab;
	i = (val == "cat") ? 0 : 1;
	j = (i == 0) ? 1 : 0;
	lab = $(".linkCategory label");
	lab.eq(i).removeClass("inactive_cat");
	lab.eq(j).addClass("inactive_cat");
	$(".paneCategory").eq(j).slideUp("slow", function() {
		$(".paneCategory").eq(i).slideDown("slow");
	});
}