// MMSN template
// Copyright exorbyte GmbH, 2010. All rights reserved.

//var servletUrl = "http://localhost:8080/ZVAB/mmsn";
var servletUrl = "http://suggest.zvab.com/mmsn";
var search_field = "one";

// all number of lines include the headline
var def_num_expanded = new Array(6, 6, 11);
var atm_num_expanded = new Array(6, 6, 11);
// expand parameters
var reduce_to = 3;
var expand_to = 20;
var expand_to_more = 32;



function snSetup($) {
	function myCallback(event, data, formatted, value) {
		redirectUrl = "http://www.zvab.com/advancedSearch.do?";
		set_query_to_cookie(value);
		switch (data.SN_type) {
			case "author":
				location.assign(redirectUrl + "author="+buildUrl(formatted, -1)+"&ref=suggest01");
				//jQuery("#suggest1").triggerSearch(formatted);
				break;
			case "title":	
				location.assign(redirectUrl +"title=%22"+buildUrl(formatted, -1)+"%22&ref=suggest02");
				break;
			case "title_author":	
				if(data.author_cluster == "") {
					location.assign(redirectUrl +"title=%22"+buildUrl(formatted, 4)+"%22&ref=suggest03");
				} else {
					location.assign(redirectUrl + "title=%22"+buildUrl(formatted, 4)+"%22&author="+
						buildUrl(data.author_cluster, 3) +"&ref=suggest03");
					}
				
				break;
		}
	}

	$("#suggest1").result(myCallback);
 
	// To send the input value to the proxy script for use in eg the Keywords
	// field, simply add 'Keywords: getInputValue' to the list of extraParams
	// in the call to autocomplete() below.
	function getInputValue() {
		return $("#suggest1").val();
	}

	function formatRow(row) {
		var content = "";
		// headline
		switch (row.SN_value) {
			case "author":
				content = "Autoren";
				// check if more hits are avaible or is expanded
				if(row.seller_id > (def_num_expanded[0]-1))
					content += " - " + formatView(row.SN_value); 
				break;
			case "title":
		 		content = "Titel";
				// check if more hits are avaible or is expanded
				if(row.seller_id > (def_num_expanded[1]-1))
					content += " - " + formatView(row.SN_value); 
				break;
			case "title_author":
		 		content = "Autor &amp; Titel";
				// check if more hits are avaible or is expanded
				if(row.seller_id > (def_num_expanded[2]-1))
					content += " - " + formatView(row.SN_value); 						
				break;				
		}
		// item
		switch (row.SN_type) {
			case "author":
				content = row.SN_value;
				break;
			case "title":
				content = row.SN_value;
				break;
			case "title_author":
				var title = row.SN_value;
				if(title == "")
					title = row.title;
				
				if(row.author_cluster == "") 
					content = "<span class='sugg_title' title=\"" + title + "\">" + title + "</span>";
				else
					content = "<span class='sugg_author' title=\"" + row.author_cluster +
					":  "+ title + "\">" + row.author_cluster + ":</span> " +
						"<span class='sugg_title' title=\"" + row.author_cluster + ":  " +
						title + "\">" + title + "</span>";
				break;				
		}
		return '' + content + '';
	}

	$("#suggest1").autocomplete(servletUrl, {
		max: 100,
		extraParams: { sn_type: search_type("default"), sn_type_mode:"APPROX"},
		formatItem: formatRow,
		formatHeader: formatHead,
		formatFooter: formatFoot,
		delay: 300,
		minChars: 3,
		dataType: "jsonp",
		highlight: false
	}).focus();
}

/**
*
* HELPER
*
*/
// builds the url to redirect 
function buildUrl(formatted, maxWords) {
	formatted = formatted.replace(/&/g, "");
	var query = formatted.split(" ");
	var result;
	for (var i = 0; i < query.length && (i < maxWords || maxWords == -1); ++i) {
		if(i == 0 )
			result = query[i];
		else
			result += "+" + query[i];
	}
	return result;
}


// The Header
function formatHead() {
	return "Suchvorschl&auml;ge";
}

// The Footer with the more link. Just show if title_author is expanded.
function formatFoot() {
	if(get_exp("title_author"))
		return formatView("title_author_more");
	return "";
}

/**
*
* EXPAND FUNCTIONS
*
*/
//Helper Functions for the "more .." Link in the simple search form SN
function formatView(cat) {
	if ( get_exp(cat) ) {
		return "<span class='sugg_expand'><a href='javascript:void(0);' " +
			"onmousedown='fewerHits(\""+cat+"\");'>Weniger ...</a></span>";	
	}
	return "<span class='sugg_expand'><a href='javascript:void(0);' " + 
		"onmousedown='moreHits(\""+cat+"\");'>Mehr ... </a></span>";
}

// Get more Hits
function moreHits(cat) {
	jQuery("#suggest1").setOptions({
		extraParams: { sn_type: search_type(cat), sn_type_mode:"APPROX"}
	});
	jQuery("#suggest1").blur();
	timeout = setTimeout(triggerSN, 250);
}

// Get fewer Hits	
function fewerHits(cat) {
	jQuery("#suggest1").setOptions({
		extraParams: {sn_type: search_type(cat), sn_type_mode:"APPROX"}
	});
	jQuery("#suggest1").blur();
	jQuery("#suggest1").triggerSearch(jQuery("#suggest1").val());
	timeout = setTimeout(triggerSN, 250);
}

// Perform search
function triggerSN() {
  jQuery("#suggest1").triggerSearch(jQuery("#suggest1").val());
}

// Show if a category is expanded
// cat - the category to check
function get_exp(cat) {
	switch (cat) {
		case "author":
			if( atm_num_expanded[0] == expand_to )
				return true;
			break;
		case "title":	
			if( atm_num_expanded[1] == expand_to )
				return true;
			break;	
		case "title_author":	
			if( atm_num_expanded[2] == expand_to || atm_num_expanded[2] == expand_to_more )
				return true;
			break;
		case "title_author_more":	
			if( atm_num_expanded[2] == expand_to_more )
				return true;
			break;
	}
	return false;
}

// build the search type string passed by sn_type (one-6-6-11)
function search_type(cat) {
	if (get_exp(cat)) {
		// Fewer
		for (i=0; i < def_num_expanded.length; i++)
			atm_num_expanded[i] = def_num_expanded[i];
	} else {
		// More
		switch (cat) {
			case "author":
				atm_num_expanded[0] = expand_to;
				atm_num_expanded[1] = reduce_to;
				atm_num_expanded[2] = reduce_to;
				break;
			case "title":
				atm_num_expanded[0] = reduce_to;
				atm_num_expanded[1] = expand_to;
				atm_num_expanded[2] = reduce_to;
				break;			
			case "title_author":
				atm_num_expanded[0] = reduce_to;
				atm_num_expanded[1] = reduce_to;
				atm_num_expanded[2] = expand_to;
				break;
			case "title_author_more":
				atm_num_expanded[0] = reduce_to;
				atm_num_expanded[1] = reduce_to;
				atm_num_expanded[2] = expand_to_more;
				break;				
		}		
	}
	return search_field+"-"+atm_num_expanded[0]+"-"+atm_num_expanded[1]+"-"+atm_num_expanded[2];
}

/**
*
* COOKIE FUNCTIONS
*
*/
// update the suggest as set by cookie exorbyte_query and exorbyte_sn_type
function set_suggest() {
	var type_cookie = jQuery.cookie('exorbyte_sn_type');
	if(type_cookie != null) {
		type_cookie = type_cookie.split("|");
		var atm = type_cookie[0].split("-")
		atm_num_expanded[0] = atm[1];
		atm_num_expanded[1] = atm[2];
		atm_num_expanded[2] = atm[3];
		
		jQuery('#suggest1').attr("value", jQuery.cookie('exorbyte_query'));		
		jQuery("#suggest1").setOptions({
			extraParams: {sn_type: type_cookie[0], sn_type_mode:"APPROX"}
		});
		jQuery("#suggest1").blur();
		timeout = setTimeout(triggerSN, 200);
	}
}

// Sets the cookie with the last search 
// Input	query	the query of the user
function set_query_to_cookie(query) {
	var date = new Date();
	date.setTime(date.getTime() + (1 * 60 * 1000));
	type = search_field+"-"+atm_num_expanded[0]+"-"+atm_num_expanded[1]+"-"+atm_num_expanded[2];
	jQuery.cookie('exorbyte_query', query, { expires: date , path: '/' });
	jQuery.cookie('exorbyte_sn_type', type, { expires: date , path: '/' });
}


// update cookie as status of checkbox 
// Input	id_checkbox					ID der checkbox
function update_cookie(id_checkbox) {
	if ( document.getElementById(id_checkbox).checked == false ) {
		jQuery.cookie('exorbyte_searchnavigator', 'true', { expires: 365, path: '/' });
		jQuery('#suggest1').unautocomplete();
	} else {
		jQuery.cookie('exorbyte_searchnavigator', 'false', { expires: 365,  path: '/' });
		snSetup(jQuery);
	}
}

// update checkbox status as set by cookie
function update_checkbox() {
	var cookie = jQuery.cookie('exorbyte_searchnavigator');
	if (cookie == "false") {
		jQuery('input[name=check_sn]').attr('checked', 'checked');
	} else {
		jQuery('input[name=check_sn]').attr('checked', '');
	}
}
