// MMSN template
// Copyright exorbyte GmbH, 2010. All rights reserved.

var servletUrl = "http://suggest.zvab.com/New_140411/mmsn-new";

/*
* number of hits in the result (including the headline)
* author, title, title_author (anywords) , author_field, author_no_ctx, title_field, title_no_ctx
*/
var def_num_expanded = new Array(6, 6, 11, 11, 5, 11, 5);
var atm_num_expanded = new Array(6, 6, 11, 11, 5, 11, 5);
// expand parameters
var reduce_to = 3;
var no_ctx_expand_to = 10;
var expand_to = 20;
var expand_to_more = 32;

// author & title field
var show_more_link = true;

// URL to redirect after an event
redirectUrl = "http://www.zvab.com/advancedSearch.do?";

function snSetup($) {
	

	
	
	/*
	* The function reacts on all click events and checks which searchfield is used. 
	* Getting an event of the field anyWords the user will be redirected with the 
	* corresponding parameter values to the zvab search.		
	*/
	function myAnyCallback(event, data, formatted, value) {
		
		// store input in cookie	
		set_query_to_cookie("anyWords", value);
		var couponSearch = ($('#couponsBasicSearch').is(':checked') ? '&mediantisCoupons=on' : '');
		
		switch (data.SN_type) {
			// Field anyWords - click on an author
			case "author":
				location.assign(redirectUrl + "author="+buildUrl(formatted, -1)+"&iref=suggest01" + couponSearch);
				break;
			// Field anyWords - click on a title
			case "title":	
				location.assign(redirectUrl +"title=%22"+buildUrl(formatted, -1)+"%22&iref=suggest02" + couponSearch);
				break;
			// Field anyWords - click on a title_author hit 
			case "title_author":	
				if(data.author_cluster == "") {
					location.assign(redirectUrl + "title=%22"+buildUrl(formatted, 4)+"%22&iref=suggest03" + couponSearch);
				} else {
					location.assign(redirectUrl + "title=%22"+buildUrl(formatted, 4)+"%22&author="+
						buildUrl(data.author_cluster, 2) +"&iref=suggest03" + couponSearch);
				}
				break;
		}
	}
		
	function formatAnyWords(row) {
			var content = "";
			// headline
			switch (row.SN_value) {
				case "author":
					content = "Autoren";
					// check if more hits are avaible or is expanded
					if(row.free_search > (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.free_search > (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.free_search > (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 + '';
		}

	// anyWords functions
	$("#anyWords").result(myAnyCallback);
 
	function getInputValue() {
		return $("#anyWords").val();
	}

	$("#anyWords").autocomplete(servletUrl, {
		max: 100,
		extraParams: { sn_type: search_type(""), sn_type_mode:"APPROX"},
		formatItem: formatAnyWords,
		formatHeader: formatHead,
		formatFooter: formatFoot,
		delay: 300,
		minChars: anyWordsMinChars,
		dataType: "jsonp",
		highlight: false
	});

	
	/**********************
	* author field & title field functions	
	**********************/
	
	function formatRow(row) {
		var html = "";
		switch (row.SN_type) {
			case "cat_1":
				if(row.free_search < (def_num_expanded[3]-1) || row.free_search < (def_num_expanded[4]-1) ) {
					show_more_link = false;
				} else {
					show_more_link = true;
				}
				if(row.SN_value == "title_field")  {
					html = "Titelvorschläge mit Autor: \"" + formatString(getAuthorInputValue(),23) + "\"";
				} else if(row.SN_value == "title_no_ctx")  {
					html ="Beste Titelvorschläge";
				} else if(row.SN_value == "author_field")  {
					html = "Autorvorschläge mit Titel: \"" + formatString(getTitleInputValue(),23) + "\"";
				} else if(row.SN_value == "author_no_ctx")  {
					html ="Beste Autorenvorschläge";
				} else {
					html = row.SN_value;
				}
				break;
			
			case "author_no_ctx":			
				html = "<span class='ac_author_col' title=\"" + row.SN_value + "\">" + 
					formatString(row.SN_value, 38) + "</span>";
				if( false && is_context_set("title_field")) {
					html += "<span class='ac_title_col' title=\"" + row.title_norm + "\">" + 
						formatString(row.title_norm, 38) + "</span>";
				}
				break;
			case "author_field":			
				html = "<span class='ac_author_col' title=\"" + row.SN_value + "\">" + 
					formatString(row.SN_value, 38) + "</span>";
				html += "<span class='ac_title_col' title=\"" + row.title_norm + "\">" + 
					formatString(row.title_norm, 38) + "</span>";
				break;
			
			case "title_no_ctx":
				if( false && is_context_set("author_field")) {
					html = "<span class='ac_author_col' title=\"" + row.SN_value + "\">" + 
						formatString(row.author_norm, 50) + "</span>";
				}
				html +=  "<span class='ac_title_col' title=\"" + row.title_norm + "\">" +
					formatString(row.title_norm, 50) + "</span>";
				break;			
			case "title_field":						
				html = "<span class='ac_author_col' title=\"" + row.SN_value + "\">" + 
					formatString(row.author_norm, 50) + "</span>";
				html +=  "<span class='ac_title_col' title=\"" + row.title_norm + "\">" +
					formatString(row.title_norm, 50) + "</span>";
				break;
		}
		return html;
	}
	
		
	/**********************
	* author functions	
	**********************/
	
	/*
	* The function reacts on all click events and checks which searchfield is used. 
	* Getting an event of the field anyWords the user will be redirected with the 
	* corresponding parameter values to the zvab search.		
	*/
	function myAuthorCallback(event, data, formatted, value) {
	
		var couponSearch = ($('#couponsBasicSearch').is(':checked') ? '&mediantisCoupons=on' : '');
		// store input in cookie
		set_query_to_cookie("author_field", value);
		// react on the event
		if(is_context_set("title_field") && data.SN_type != "author_no_ctx") {
			// if both fields are set search
			location.assign(redirectUrl + "title=%22"+buildUrl(data.title_norm, 4)+"%22&author="+
				buildUrl(formatted, 2) +"&iref=suggest07" + couponSearch);
		} else {
			// set focus to the title field
			jQuery("#title").val("");
			setTimeout(setFocusTitle, 120);
		}
	}
	
	function setFocusTitle() {
		jQuery("#title").triggerSearch(" ").focus();
	}
	
	$("#author").result(myAuthorCallback);
	
	
	$("#author").autocomplete(servletUrl, {
		max: 100,
		extraParams: { 	sn_type: search_type("author_field_init"),
						sn_type_mode:"APPROX", 
						title_norm: getTitleInputValue, 
						title_norm_mode: "COMPLETE" },
		formatItem: formatRow, 
		formatHeader: formatHead,
		formatFooter: formatAuthorFoot,
		delay: 300,
		width:534,
		minChars: authorMinChars,
		dataType: "jsonp",
		highlight: false
	});
	
	
	
	/**********************
	* title functions	
	**********************/	
	
	/*
	* The function reacts on all click events and checks which searchfield is used. 
	* Getting an event of the field anyWords the user will be redirected with the 
	* corresponding parameter values to the zvab search.		
	*/
	function myTitleCallback(event, data, formatted, value) {
		
		var couponSearch = ($('#couponsBasicSearch').is(':checked') ? '&mediantisCoupons=on' : '');
		// store input in cookie
		set_query_to_cookie("title_field", value);
		// react on the event
		if(is_context_set("author_field") && data.SN_type != "title_no_ctx") {
			// if both fields are set search
			location.assign(redirectUrl + "title=%22"+buildUrl(formatted, 4)+"%22&author="+
				buildUrl(data.author_norm, 2) +"&iref=suggest07" + couponSearch);
		} else {
			jQuery("#author").val("");
			setTimeout(setFocusAuthor, 120);
		}
	}	
	
	function setFocusAuthor() {
		// set focus to the author field
		jQuery("#author").triggerSearch(" ").focus();
	}
	
	$("#title").result(myTitleCallback);
	
	$("#title").autocomplete(servletUrl, {
		max: 100,
		extraParams: { 	sn_type: search_type("title_field_init"), 
						sn_type_mode:"APPROX",
						author_norm: getAuthorInputValue,
						author_norm_mode: "COMPLETE"},
		formatItem: formatRow,
		formatHeader: formatHead,
		formatFooter: formatTitleFoot,		
		width:534,
		leftOffset: -268,
		delay: 300,
		minChars: titleMinChars,
		dataType: "jsonp",
		highlight: false
	});
	
	 $("#submit").click(function () { 
		set_query_to_cookie("default", "");
	 });	
}

function anyWordsMinChars() {
	return 3;
}

function titleMinChars() {
	if(getAuthorInputValue().length > 0) {
		return 0;
	}
	return 3;
}

function authorMinChars() {
	if(getTitleInputValue().length > 0) {
		return 0;
	}
	return 3;
}

/**
*
* 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='changeNumHits(\""+cat+"\");'>Weniger ...</a></span>";	
	}
	return "<span class='sugg_expand'><a href='javascript:void(0);' " + 
		"onmousedown='changeNumHits(\""+cat+"\");'>Mehr ... </a></span>";
}

// Get more Hits
function changeNumHits(cat) {
	if(cat == "title_field") {
		jQuery("#title").setOptions({
			extraParams: {	sn_type: search_type(cat),
							sn_type_mode:"APPROX",
							author_norm: getAuthorInputValue,
							author_norm_mode: "COMPLETE",
							minChars: authorMinChars
							}});
		jQuery("#title").blur();
		timeout = setTimeout(triggerTitleSN, 250);

	} else if (cat == "author_field") {
		jQuery("#author").setOptions({
			extraParams: { 	sn_type: search_type(cat),
							sn_type_mode:"APPROX",
							title_norm: getTitleInputValue, 
							title_norm_mode: "COMPLETE" ,
							minChars: titleMinChars
						  }});
		jQuery("#author").blur();
		timeout = setTimeout(triggerAuthorSN, 250);	
	} else {
		jQuery("#anyWords").setOptions({
			extraParams: { sn_type: search_type(cat), sn_type_mode:"APPROX"}
		});
		jQuery("#anyWords").blur();
		timeout = setTimeout(triggerAnySN, 250);
	}
}

// Perform anywords search
function triggerAnySN() {
  jQuery("#anyWords").triggerSearch(jQuery("#anyWords").val());
}
// Perform author search
function triggerAuthorSN() {
	if(jQuery("#author").val().length > 0) {
		jQuery("#author").triggerSearch(jQuery("#author").val());
	} else {
		jQuery("#author").triggerSearch(" ");	
	}
}
// Perform title search
function triggerTitleSN() {
	if(jQuery("#title").val().length > 0) {
		jQuery("#title").triggerSearch(jQuery("#title").val());
	} else {
		jQuery("#title").triggerSearch(" ");
	}
}

// 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;
		case "author_field":
			if( atm_num_expanded[3] == expand_to )
				return true;
			break;
		case "title_field":
			if( atm_num_expanded[5] == expand_to )
				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;	
			case "author_field":
				atm_num_expanded[3] = expand_to;
				atm_num_expanded[4] = no_ctx_expand_to;
				break;
			case "title_field":
				atm_num_expanded[5] = expand_to;
				atm_num_expanded[6] = no_ctx_expand_to;
				break;
		}		
	}
	switch (cat) {
		case "author_no_ctx":
		case "author_field_init":
		case "author_field":
			return "author-" + atm_num_expanded[3] + "-" + atm_num_expanded[4];

		case "title_no_ctx":
		case "title_field_init":
		case "title_field":
			return "title-" + atm_num_expanded[5] + "-" + atm_num_expanded[6];

		default:
			return "anyWords-"+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() {
	// read the cookies
	var type_cookie = jQuery.cookie('exorbyte_sn_type');
	var sn_values = jQuery.cookie('exorbyte_query');
	
	if(type_cookie != null && sn_values != null ) {
		sn_values = sn_values.split("|");
		type_cookie = type_cookie.split("-");
		var trigger_sn = 0;
		jQuery('#anyWords').attr("value", sn_values[0]);		
		jQuery('#author').attr("value", sn_values[1]);		
		jQuery('#title').attr("value", sn_values[2]);	
		
		// set the field according to the last event / query
		switch(type_cookie[0]) {
			case "anyWords":
				atm_num_expanded[0] = type_cookie[1];
				atm_num_expanded[1] = type_cookie[2];
				atm_num_expanded[2] = type_cookie[3];
				
				jQuery("#anyWords").setOptions({
					extraParams: {sn_type: search_type(type_cookie[0]), sn_type_mode:"APPROX"}
				});
				jQuery("#anyWords").blur();
				timeout = setTimeout(triggerAnySN, 200);
				trigger_sn = 1;
				break;
			case "author":
				atm_num_expanded[3] = type_cookie[1];
				atm_num_expanded[4] = type_cookie[2];
				
				jQuery("#author").setOptions({
					extraParams: {	sn_type: search_type("author_field"),
									sn_type_mode:"APPROX",
									title_norm: getTitleInputValue, 
									title_norm_mode: "COMPLETE" 
								}});
				jQuery("#author").blur();
				timeout = setTimeout(triggerAuthorSN, 200);
				trigger_sn = 1;
				break;
			case "title":
				atm_num_expanded[5] = type_cookie[1];
				atm_num_expanded[6] = type_cookie[2];
				
				jQuery("#title").setOptions({
					extraParams: {	sn_type: search_type("title_field"),
									sn_type_mode:"APPROX",
									author_norm: getAuthorInputValue,
									author_norm_mode: "COMPLETE"
								}});
				jQuery("#title").blur();
				timeout = setTimeout(triggerTitleSN, 300);
				trigger_sn = 1;
				break;
		}
	} else {
		jQuery("#anyWords").focus();
	}
}

// Sets the cookie with the last search 
// Input	q	the query of the user
function set_query_to_cookie(cat, q) {
	var date = new Date();
	date.setTime(date.getTime() + (1 * 60 * 1000));
	var query = "";
	if(cat == "anyWords") {
		query += q + "|";
		query += getAuthorInputValue() + "|";
		query += getTitleInputValue();
	} else if(cat == "author_field") {
		query += getAnywordsInputValue() + "|";
		query += q + "|";
		query += getTitleInputValue();
	} else if(cat == "title_field") {
		query += getAnywordsInputValue() + "|";
		query += getAuthorInputValue() + "|";
		query += q;	
	} else {
		
		query += getAnywordsInputValue() + "|";
		query += getAuthorInputValue() + "|";
		query += getTitleInputValue();		
	}
	//if(getAuthorInputValue().length > 0 ) getTitleInputValue() > 0 )
	type = search_type(cat);
	jQuery.cookie('exorbyte_query', query, { expires: date , path: '/' });
	jQuery.cookie('exorbyte_sn_type', type, { expires: date , path: '/' });
}



// Activates or Deactivates the autosuggest
// 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('#anyWords').unautocomplete();
		jQuery('#author').unautocomplete();
		jQuery('#title').unautocomplete();
	} else {
		jQuery.cookie('exorbyte_searchnavigator', 'false', { expires: 365,  path: '/' });
		snSetup(jQuery);
	}
}

function update_cookie_snhead() {
	jQuery.cookie('exorbyte_searchnavigator', 'true', { expires: 365, path: '/' });
	jQuery('input[name=check_sn]').attr('checked', '');
	jQuery('#anyWords').unautocomplete();
	jQuery('#author').unautocomplete();
	jQuery('#title').unautocomplete();
}

// update checkbox status as set by cookie
function update_checkbox() {
	/* Turn off standard autocompletion */
	$("#anyWords").attr('autocomplete', 'off');
	$("#author").attr('autocomplete', 'off');
	$("#title").attr('autocomplete', 'off');
	var cookie = jQuery.cookie('exorbyte_searchnavigator');
	if (cookie != "true") {
		jQuery('input[name=check_sn]').attr('checked', 'checked');
	} else {
		jQuery('input[name=check_sn]').attr('checked', '');
	}
}


/**
*
* 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;
}

function is_context_set(field) {
	if(field == "title_field") {
		var title = getTitleInputValue();
		if( title == "undefined" || trim(title).length > 0 ) {
			return true;
		}	
	} else {
		var author = getAuthorInputValue();
		if( title == "undefined" || trim(author).length > 0 ) {
			return true;
		}
	}
	return false;	
}

function trim(zeichenkette) {
	return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function getTitleInputValue() {
		return jQuery("#title").val();
}

function getAuthorInputValue() {
		return jQuery("#author").val();
}	

function getAnywordsInputValue() {
		return jQuery("#anyWords").val();
}	

/**
*
* FORMATTER
*
*/

function formatString(string, maxLength) {
	if(string.length > maxLength) {
		return string.substring(0, maxLength) + "..."
	}
	return string;
}



// The Header
function formatHead() {
	return "<a href='javascript:void(0);' " +
			"onmousedown='update_cookie_snhead();'>Suchvorschl&auml;ge ausschalten</a>";
}

// 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 "";
}

function formatAuthorFoot() {
	if(show_more_link)
		return formatView("author_field");
	return "";
}

function formatTitleFoot() {
	if(show_more_link)
		return formatView("title_field");
	return "";
}

