// Automatic jump from dropdownmeny
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
/*
* Show and and hide an element
*
* @author Anton
*
* Opening link example <a onclick="showDiv('div_to_show_id')">Övrigt</a>
* All closing links should have <a onclick=hideDiv('div_to_close_id')>Hoppa hit</a>
* 
*/

function showDiv(id) {
	var div = document.getElementById(id);
	if (div.style.zIndex == 1000) {
		hideDiv(id);
	} else {
		div.style.zIndex = 1000;
		div.style.visibility = "visible";
	}
}
function hideDiv(id) {
	var div = document.getElementById(id);
	div.style.zIndex = -100;
	div.style.visibility = "hidden";
}
/*
* Return the number of the GK sound
* 
* @author Anton
*
* 
*/
function getGkNumber(id) {
	var select_tag = document.getElementById(id);
	for (i=0; i<select_tag.length; i++) {
		if (select_tag.options[i].selected) {
			return select_tag.options[i].value;
		}
	}
}


/*
* Dynamic search
* 
*/
//Keep track of the last search made for each search component
var dsLastSearchValue = new Array();

//Cache the search results for each search component
var dsSearchCache = new Array();

//Keep track of the selected item for each search component
var dsSelectedItem = new Array();

//String prototype function to trim the whitespaces from the string
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//Make sure all search containers are hidden when document is ready
$(document).ready(function () {
	$('div.dynamic_search_container').hide();
});

$(document).click(mouseClickFunction);

//Hides the search container div when the user clicks
function mouseClickFunction(e) {
	if (e.target)
		sourceElement = e.target;
	else if (e.srcElement)
		sourceElement = e.srcElement;
	if (sourceElement.nodeType == 3) // for Safari..
		sourceElement = sourceElement.parentNode;		
	if(sourceElement.tagName.toLowerCase()!='input')
		hideDynamicSearchList();
}

//Keydown function used for keyboard navigation
function dynamicSearchKeydownFunction(fieldId, e) {
	//Up arrow
	if(e.keyCode==38){
		if (!dsSelectedItem[fieldId])
			return;
		if (!dsSelectedItem[fieldId].previousSibling)
			return;
		dynamicSearchLinkOut(dsSelectedItem[fieldId]);
		dynamicSearchLinkOver(dsSelectedItem[fieldId].previousSibling, fieldId);
	}
	//Down arrow
	if(e.keyCode==40){
		if (!dsSelectedItem[fieldId]){
			newItem = $('div#' + fieldId + '_dynamic_search_container div:first').get(0);
			if (newItem) 
				dynamicSearchLinkOver(newItem, fieldId);
			return;
		}
		if (!dsSelectedItem[fieldId].nextSibling)
			return;
		dynamicSearchLinkOut(dsSelectedItem[fieldId]);
		dynamicSearchLinkOver(dsSelectedItem[fieldId].nextSibling, fieldId);
	}
	//Enter or tab
	if(e.keyCode==13 || e.keyCode==9){
		if (dsSelectedItem[fieldId])
			setSearch(fieldId, dsSelectedItem[fieldId].innerHTML);
			hideDynamicSearchList();
		if (e.keyCode==13) {
      //prevent form submit
      e.cancelBubble = true;
      e.returnValue = false;
      if (e.stopPropagation) e.stopPropagation();
      if (e.preventDefault) e.preventDefault();
			return false;
			}
		else
			return true;
	}
	//Escape
	if(e.keyCode==27){
		hideDynamicSearchList();
	}	
}

//Returns the current actual search value from the whole input
//string which can be a comma separated list
function getSearchValueFromInput(inputValue) {
	lastCommaIndex = inputValue.lastIndexOf(',');
	if (lastCommaIndex == -1)
		return inputValue.trim();
	return inputValue.substring(lastCommaIndex + 1).trim();
}

//Performs the search by making a request to the specified
//search service if needed
function performDynamicSearch(fieldId, searchURL, minimumLetters, e) {
  if (e.keyCode==13)
    //enter key
    return;
	searchValue = getSearchValueFromInput($('input#' + fieldId).val());
	//do not perform dynamic search unless there are characters
	if (searchValue.length < minimumLetters) {
		hideDynamicSearchList();
		dsLastSearchValue[fieldId] = null;
		return;
		}
	if (dsLastSearchValue[fieldId] == searchValue)
		return;
	dsSelectedItem[fieldId] = false;
	cachedValue = getDynamicSearchCache(fieldId, searchValue);
	if (cachedValue) {
		dynamicSearchSuccessFunction(cachedValue, fieldId);
		dsLastSearchValue[fieldId] = searchValue;
		return;
		}
	$.ajax({url: searchURL + encodeURI(searchValue),
		type: 'GET',
		dataType: 'xml',
		error: function() {},
		success: function (xml) {
			addDynamicSearchCache(fieldId, searchValue, xml);
			dynamicSearchSuccessFunction(xml, fieldId);
			dsLastSearchValue[fieldId] = searchValue;
			}
		});
}

//Fills the search container div with the result and displays the container
function dynamicSearchSuccessFunction(xml, fieldId) {
	dsListDivName = 'div#' + fieldId + '_dynamic_search_container';
	dsListDiv = $(dsListDivName);
	//dsListDiv.slideUp('fast');
	dsListDiv.html('');
	$(xml).find('item').each(function () {
		itemText = $(this).text();
		itemDiv = '<div onmouseover="dynamicSearchLinkOver(this, \'' + fieldId + '\');" ';
		itemDiv += 'onmouseout="dynamicSearchLinkOut(this);" ';
		itemDiv += 'onclick="setSearch(\'' + fieldId + '\',this.innerHTML);" ';
		itemDiv += 'class="dynamic_search_link"></div>';
		$(itemDiv).html(itemText).appendTo(dsListDivName);
	});
	if (dsListDiv.html() != '')
		dsListDiv.slideDown('fast');
	else
		dsListDiv.hide();
}

//Hides all search result lists
function hideDynamicSearchList() {
	dsListDiv = $('div.dynamic_search_container');
	dsListDiv.slideUp('fast');
	dsSelectedItem = new Array();
}

//Mouse over link 
function dynamicSearchLinkOver(itemDiv, fieldId) {
	itemDiv.className = 'dynamic_search_link_over';
	dsSelectedItem[fieldId] = itemDiv;
}

//Mouse out from link 
function dynamicSearchLinkOut(itemDiv) {
	itemDiv.className = 'dynamic_search_link';
}

//Sets the selected value to field
function setSearch(fieldId, selectedValue) {
	inputValue = $('#'+fieldId).val();
	lastCommaIndex = inputValue.lastIndexOf(',');
	if (lastCommaIndex == -1) {
		$('#'+fieldId).val(selectedValue);
		return;
		}
	inputValue = inputValue.substring(0, lastCommaIndex + 1) + ' ';
	inputValue += selectedValue;
	$('#'+fieldId).val(inputValue);
}

//Returns the cached value for a specific search string
function getDynamicSearchCache(fieldId, searchValue) {
	searchValue = searchValue.toLowerCase();
	if (!dsSearchCache[fieldId] || !dsSearchCache[fieldId][searchValue])
		return null;
	return dsSearchCache[fieldId][searchValue];		
}

//Adds the search result for a specific search value to the cache
function addDynamicSearchCache(fieldId, searchValue, xml) {
	searchValue = searchValue.toLowerCase();
	if (!dsSearchCache[fieldId])
		dsSearchCache[fieldId] = new Array();
	dsSearchCache[fieldId][searchValue] = xml;
}
/*
* Dynamic search end
* 
*/

/**
 * Report content
 */
 function reportContent(id, contentType, contentOwner, URL, field, userID) {
	$.ajax({url: URL + '?id=' + id + '&content_type=' + contentType + '&content_owner=' + contentOwner,
	type: 'GET',
	dataType: 'html',
	error: function(e1, e2, e3) {alert('error: ' + e1 +' - '+ e2+' - '+ e3) },
	success: function (htmlResponse) {
		$(field).replaceWith(htmlResponse);
		}
	});
}