var strHost = location.href.replace(/frontend\/(index\.php)?.*$/, '');	//URL zum Server
var intLengthProfileInList = 200;	//Anzahl der Zeichen, die im Profile in der Liste der Suchergebnisse angezeigt werden

var objHTTPServiceSearch = new httpServiceObject(strHost + 'ajax_interface/search.php', 'handleSearchResult');
var strIdActiveResult = '';

function initSearch()
{
	try
	{
		if (location.search == '')
		{
			throw ('keine Parameter übergeben');
		}
		var arrParameter = location.search.replace(/^\?/, '').split(/&/);
		if (arrParameter.length == 0)
		{
			throw ('ungültiger Parameterstring');
		}
		var objForm = document.forms['frm_search'];
		for (var i = 0; i < arrParameter.length; i++)
		{
			var arrValues = arrParameter[i].split(/=/);
			if (document.forms['frm_search'].elements[arrValues[0]] == null)
			{
				throw ('Parametername "' + arrValues[0] + '" ist ungültig.');
			}
			document.forms['frm_search'].elements[arrValues[0]].value = unescape(arrValues[1]);
		}
		sendSearchRequest(document.forms['frm_search']);
	}
	catch (exc)
	{
		//console.log(exc);
	}
}

function sendSearchRequest(in_varSubject)
{
	var strSearch = '';
	if (typeof(in_varSubject) == 'object')
	{
		strSearch += in_varSubject.elements['immediate_actions'].value != 'all' ? (strSearch != '' ? '&' : '') + 'immediate_actions=' + getStringFromArray(getMultipleSelectValues(in_varSubject.elements['immediate_actions']), ',') : '';
		strSearch += in_varSubject.elements['operating_sectors'].value != 'all' ? (strSearch != '' ? '&' : '') + 'operating_sectors=' + getStringFromArray(getMultipleSelectValues(in_varSubject.elements['operating_sectors']), ',') : '';
		strSearch += in_varSubject.elements['building_services'].value != 'all' ? (strSearch != '' ? '&' : '') + 'building_services=' + getStringFromArray(getMultipleSelectValues(in_varSubject.elements['building_services']), ',') : '';
		strSearch += in_varSubject.elements['management'].value != 'all' ? (strSearch != '' ? '&' : '') + 'management=' + getStringFromArray(getMultipleSelectValues(in_varSubject.elements['management']), ',') : '';
		strSearch += in_varSubject.elements['type_of_business'].value != 'all' ? (strSearch != '' ? '&' : '') + 'type_of_business=' + getStringFromArray(getMultipleSelectValues(in_varSubject.elements['type_of_business']), ',') : '';
		strSearch += in_varSubject.elements['bundesland'].value != 'all' ? (strSearch != '' ? '&' : '') + 'bundesland=' + getStringFromArray(getMultipleSelectValues(in_varSubject.elements['bundesland']), ',') : '';
		strSearch += in_varSubject.elements['catchwords'] != null && in_varSubject.elements['catchwords'].value != '' ? (strSearch != '' ? '&' : '') + 'catchwords=' + in_varSubject.elements['catchwords'].value.replace(/\+/g, '%2B') : '';
	}
	else if (typeof(in_varSubject) == 'string')
	{
		strSearch += 'company=' + in_varSubject;
	}
	objHTTPServiceSearch.send(strSearch);
	document.getElementsByTagName('body')[0].style.cursor = 'wait';
	document.getElementById('btn_start_search').style.cursor = 'wait';
	strIdActiveResult = '';
	return false;
}

function handleSearchResult()
{
	document.getElementById('headline').innerHTML = objHTTPServiceSearch.lastResult.getElementsByTagName('cases')[0].getAttribute('subject') + ' (' + objHTTPServiceSearch.lastResult.getElementsByTagName('cases')[0].childNodes.length + ' Treffer)';
	//bei Fehler
	if (objHTTPServiceSearch.lastResult.getElementsByTagName('errors').length > null)
	{
		updateResultListWithError();
		updateDetailAreaWithError();
	}
	else if (objHTTPServiceSearch.lastResult.getElementsByTagName('cases')[0].childNodes.length == 0)
	{
		updateResultListWithEmptyResult();
		updateDetailAreaWithEmptyResult();
	}
	else
	{
		updateResultListWithList();
		updateDetailAreaWithSummary();
	}
	document.getElementsByTagName('body')[0].style.cursor = 'default';
	document.getElementById('btn_start_search').style.cursor = 'default';
}

function updateResultListWithError()
{
	document.getElementById('search_top').innerHTML = '';
	document.getElementById('search_top').style.overflow = 'auto';
	var strHtml = '';
	for (var i = 0; i < objHTTPServiceSearch.lastResult.getElementsByTagName('errors').length; i++)
	{
		var objError = objHTTPServiceSearch.lastResult.getElementsByTagName('errors')[i];
		strHtml += '<div class="text-error">' + objError.getElementsByTagName('message')[0].firstChild.nodeValue + '</span>';
	}
	document.getElementById('search_top').innerHTML = strHtml;
}

function updateResultListWithEmptyResult()
{
	document.getElementById('search_top').innerHTML = '';
	document.getElementById('search_top').style.overflow = 'auto';
	var strHtml = '';
	strHtml += '<div class="text-copy">';
	strHtml += 'Ihre Suche ergab keine Treffer.';
	strHtml += '</div>';
	document.getElementById('search_top').innerHTML = strHtml;
}

function updateResultListWithList()
{
	document.getElementById('search_top').innerHTML = '';
	document.getElementById('search_top').style.overflow = 'auto';
	var strHtml = '';
	for (var i = 0; i < objHTTPServiceSearch.lastResult.getElementsByTagName('case').length; i++)
	{
		var objCase = objHTTPServiceSearch.lastResult.getElementsByTagName('case')[i];
		strHtml += '<div id="' + objCase.getAttribute('id') + '" class="box-list-passive" style="width:798px; padding:2px; margin-bottom:10px; cursor:pointer;" onclick="handleMouseClickResultList(this.id)" onmouseover="handleMouseOverResultList(this.id)" onmouseout="handleMouseOutResultList(this.id)">';
		strHtml += '<div class="text-head-list-passive">';
		strHtml += (i + 1) + '. ' + addSearchMarks(objCase.getElementsByTagName('company')[0].firstChild.nodeValue);
		strHtml += '</div>';
		strHtml += '<div class="text-copy">';
		var strProfile = objCase.getElementsByTagName('title')[0].firstChild != null ? addSearchMarks(objCase.getElementsByTagName('title')[0].firstChild.nodeValue) : '';
		strHtml += strProfile.length <= intLengthProfileInList ? strProfile : strProfile.substr(0, intLengthProfileInList) + ' &#8230;';
		strHtml += '</div>';
		strHtml += '</div>';
	}
	document.getElementById('search_top').innerHTML = strHtml;
}

function handleMouseClickResultList(in_strId)
{
	if (strIdActiveResult != '')
	{
		document.getElementById(strIdActiveResult).className = 'box-list-passive';
		document.getElementById(strIdActiveResult).firstChild.className = 'text-head-list-passive';
	}
	if (strIdActiveResult != in_strId)
	{
		strIdActiveResult = in_strId;
		document.getElementById(strIdActiveResult).className = 'box-list-active';
		document.getElementById(strIdActiveResult).firstChild.className = 'text-head-list-active';
	}
	else
	{
		strIdActiveResult = '';
	}
}

function handleMouseOverResultList(in_strId)
{
	if (strIdActiveResult != in_strId)
	{
		document.getElementById(in_strId).className = 'box-list-over';
	}
	updateDetailAreaWithResult(in_strId);
}

function handleMouseOutResultList(in_strId)
{
	document.getElementById(in_strId).className = 'box-list-passive';
	document.getElementById(in_strId).firstChild.className = 'text-head-list-passive';
	if (strIdActiveResult != '')
	{
		document.getElementById(strIdActiveResult).className = 'box-list-active';
		document.getElementById(strIdActiveResult).firstChild.className = 'text-head-list-active';
		updateDetailAreaWithResult(strIdActiveResult);
	}
	else
	{
		//document.getElementById('search_details').className = 'box-details-passive';
		//document.getElementById('search_details').innerHTML = '';
	}
}

function updateDetailAreaWithError()
{
	document.getElementById('search_details').className = 'box-details-passive';
	document.getElementById('search_details').innerHTML = '';
}

function updateDetailAreaWithEmptyResult()
{
	document.getElementById('search_details').className = 'box-details-active';
	document.getElementById('search_details').innerHTML = '';

	var strHtml = '';
	strHtml += '<div style="margin-bottom:10px" class="text-copy">';
	strHtml += '<h2>Ihre Suche ergab <span class="text-color">' + objHTTPServiceSearch.lastResult.getElementsByTagName('case').length + '</span> Treffer.</h2>';
	strHtml += '<div style="margin-top:15px">';
	strHtml += 'Bitte erweitern Sie Ihren Suchbereich und klicken Sie auf "neue Suche"';
	strHtml += '</div>';
	strHtml += '</div>';

	document.getElementById('search_details').innerHTML = strHtml;
}

function updateDetailAreaWithSummary()
{
	document.getElementById('search_details').className = 'box-details-active';
	document.getElementById('search_details').innerHTML = '';

	var strHtml = '';
	strHtml += '<div style="margin-bottom:10px" class="text-copy">';
	strHtml += '<h2>Ihre Suche ergab <span class="text-color">' + objHTTPServiceSearch.lastResult.getElementsByTagName('case').length + '</span> Treffer.</h2>';
	strHtml += '<div style="margin-top:15px">';
	strHtml += 'Fahren Sie mit der Maus in der Liste oben &uuml;ber einen Eintrag um die Details des Energieberaters hier anzuzeigen.<br /><br />Durch Klicken auf einen Eintrag wird dieser selektiert und die Details werden dauerhaft hier angezeigt.';
	strHtml += '<br /><br />&Uuml;ber den Men&uuml;punkt &#8222;Druckansicht&#8220; &ouml;ffnen Sie eine f&uuml;r den Druck optimierte Version der Daten des ausgew&auml;hlten Energieberaters<br />&Uuml;ber den Punkt &#8222;PDF&#8220; k&ouml;nnen Sie sich die Daten als PDF-Datei herunterladen.';
	strHtml += '</div>';
	strHtml += '</div>';

	document.getElementById('search_details').innerHTML = strHtml;
}

function updateDetailAreaWithResult(in_strId)
{
	document.getElementById('search_details').className = 'box-details-active';
	var objCase = getElementById(objHTTPServiceSearch.lastResult, in_strId);
	//Betreibsart bestimmen
	var strTypeOfBusiness = objCase.getElementsByTagName('type_of_business')[0].firstChild.nodeValue
	var strClassOfBusiness = strTypeOfBusiness == 'Gaststätte' || strTypeOfBusiness == 'Sonstiges' ? 'Gaststätte' : 'Hotel';
	document.getElementById('search_details').innerHTML = '';
	var strHtml = '';

	strHtml += '<div style="margin-bottom:10px">';
	strHtml += '<h2 style="float:left">Details</h2>';
	strHtml += '<div style="text-align:right"><a href="../frontend/print_case.php?id=' + objCase.getAttribute('id') + '" target="_blank">Druckansicht</a><a style="margin-left:20px" href="../frontend/pdf.php?id=' + objCase.getAttribute('id') + '" target="_blank">PDF</a><a style="margin-left:20px" href="mailto:' + objCase.getElementsByTagName('email')[0].firstChild.nodeValue + '">Anfrage</a></div>';
	strHtml += '</div>';

	strHtml += '<table cellpadding="0" cellspacing="0" border="0" class="text-copy" style="clear:left; width:510px">';

	if (objCase.getElementsByTagName('title')[0].firstChild != null)
	{
		strHtml += '<tr>';
		strHtml += '<td colspan="3" class="text-head-list-active">' + addSearchMarks(objCase.getElementsByTagName('title')[0].firstChild.nodeValue.replace(/\n/g, '<br />')) + '</td>';
		strHtml += '</tr>';
	}

	strHtml += '<tr>';
	strHtml += '<td colspan="3">';
	strHtml += '<h3>Betriebsbeschreibung</h3>';
	strHtml += '<div class="body-detail">';
	strHtml += '<div><strong>' + addSearchMarks(objCase.getElementsByTagName('company')[0].firstChild.nodeValue) + '</strong></div>';
	strHtml += '<div style="margin-top:5px"><strong>Betriebsart' + (objCase.getElementsByTagName('hotel_classification')[0].firstChild != null && strClassOfBusiness == 'Hotel' ? ' und Komfortklasse' : '') + ':</strong> ' + addSearchMarks(objCase.getElementsByTagName('type_of_business')[0].firstChild.nodeValue) + (objCase.getElementsByTagName('hotel_classification')[0].firstChild != null && strClassOfBusiness == 'Hotel' ? ', ' + objCase.getElementsByTagName('hotel_classification')[0].firstChild.nodeValue : '') + '</div>';
	strHtml += '<div><strong>Betriebsgröße:</strong> ' + (strClassOfBusiness == 'Hotel' ? objCase.getElementsByTagName('hotel_number_rooms')[0].firstChild.nodeValue + ' Gästezimmer' : objCase.getElementsByTagName('restaurant_number_places')[0].firstChild.nodeValue + ' Plätze') + '</div>';
	if (
				strClassOfBusiness == 'Hotel' &&
				(
					objCase.getElementsByTagName('hotel_restaurant')[0].firstChild.nodeValue == 'y' ||
					objCase.getElementsByTagName('hotel_wellness')[0].firstChild.nodeValue == 'y' ||
					objCase.getElementsByTagName('hotel_seminar_room')[0].firstChild.nodeValue == 'y' ||
					objCase.getElementsByTagName('hotel_other')[0].firstChild != null
				)
			)
	{
		strHtml += '<div><strong>Ausstattung: </strong>';
		var strRow = '';
		strRow += objCase.getElementsByTagName('hotel_restaurant')[0].firstChild.nodeValue == 'y' ? 'Restaurant' : '';
		strRow += objCase.getElementsByTagName('hotel_wellness')[0].firstChild.nodeValue == 'y' ? ', Wellness' : '';
		strRow += objCase.getElementsByTagName('hotel_seminar_room')[0].firstChild.nodeValue == 'y' ? ', Tagungsräume' : '';
		strRow += objCase.getElementsByTagName('hotel_other')[0].firstChild != null ? ', ' + objCase.getElementsByTagName('hotel_other')[0].firstChild.nodeValue : '';
		strHtml += strRow.replace(/^, /, '');
	}
	else if (
						strClassOfBusiness != 'Hotel' &&
						(
							objCase.getElementsByTagName('restaurant_seminar_room')[0].firstChild.nodeValue == 'y' ||
							objCase.getElementsByTagName('restaurant_other')[0].firstChild != null
						)
					)
	{
		strHtml += '<div><strong>Ausstattung: </strong>';
		var strRow = '';
		strRow += objCase.getElementsByTagName('restaurant_seminar_room')[0].firstChild.nodeValue == 'y' ? ', Tagungsräume' : '';
		strRow += objCase.getElementsByTagName('restaurant_other')[0].firstChild != null ? ', ' + objCase.getElementsByTagName('restaurant_other')[0].firstChild.nodeValue : '';
		strHtml += strRow.replace(/^, /, '');
	}
	strHtml += '</div>';
	strHtml += '</div>';
	strHtml += '</td>';
	strHtml += '</tr>';

	//Kontaktdaten
	strHtml += '<tr>';
	strHtml += '<td style="width:250px">';
	strHtml += '<h3>Kontaktdaten</h3>';
	strHtml += '<div class="body-detail">';
	if (objCase.getElementsByTagName('contact')[0].firstChild != null)
	{
		strHtml += '<div><strong>Ansprechpartner: </strong>' + addSearchMarks(objCase.getElementsByTagName('contact')[0].firstChild.nodeValue) + '</div>';
	}
	strHtml += '<div><strong>Telefon: </strong>' + addSearchMarks(objCase.getElementsByTagName('phone')[0].firstChild.nodeValue) + '</div>';
	if (objCase.getElementsByTagName('email')[0].firstChild != null)
	{
		strHtml += '<div><strong>E-Mail: </strong><a href="mailto:' + objCase.getElementsByTagName('email')[0].firstChild.nodeValue + '">' + addSearchMarks(objCase.getElementsByTagName('email')[0].firstChild.nodeValue) + '</a></div>';
	}
	if (objCase.getElementsByTagName('web')[0].firstChild != null)
	{
		strHtml += '<div><strong>Web: </strong><a href="http://' + objCase.getElementsByTagName('web')[0].firstChild.nodeValue + '" target="_blank">' + addSearchMarks(objCase.getElementsByTagName('web')[0].firstChild.nodeValue) + '</a></div>';
	}
	strHtml += '</div>';
	strHtml += '</td>';

	strHtml += '<td style="width:10px"></td>';

	strHtml += '<td style="width:250px">';

	//Themengebiete
	strHtml += '<h3>Themengebiete</h3>';
	strHtml += '<div class="body-detail">';
	var strRow = ''
	for (var i = 0; i < objCase.getElementsByTagName('immediate_action').length; i++)
	{
		strRow += ', ' + objCase.getElementsByTagName('immediate_action')[i].firstChild.nodeValue;
	}
	for (var i = 0; i < objCase.getElementsByTagName('operating_sector').length; i++)
	{
		strRow += ', ' + objCase.getElementsByTagName('operating_sector')[i].firstChild.nodeValue;
	}
	for (var i = 0; i < objCase.getElementsByTagName('building_service').length; i++)
	{
		strRow += ', ' + objCase.getElementsByTagName('building_service')[i].firstChild.nodeValue;
	}
	for (var i = 0; i < objCase.getElementsByTagName('management').length; i++)
	{
		strRow += ', ' + objCase.getElementsByTagName('management')[i].firstChild.nodeValue;
	}
	strHtml += strRow.replace(/^, /, '');
	strHtml += '</div>';
	strHtml += '</td>';
	strHtml += '</tr>';

	//Abbildung
	strHtml += '<td style="width:250px">';
	strHtml += '<h3>Abbildung Betrieb</h3>';
	if (objCase.getElementsByTagName('image_file_system')[0].firstChild != null)
	{
		strHtml += '<img src="../images_cases/' + objCase.getElementsByTagName('image_file_system')[0].firstChild.nodeValue.replace(/(\.\w{3,4})/, '_tn$1') + '" alt="" />';
	}
	strHtml += '</td>';

	strHtml += '<td style="width:10px"></td>';

	//Einsparung
	strHtml += '<td style="width:250px">';
	strHtml += '<h3>Verbrauchs-/Kosteneinsparung</h3>';
	strHtml += '<div class="body-detail"><strong>' + addSearchMarks(objCase.getElementsByTagName('savings')[0].firstChild.nodeValue.replace(/\n/g, '<br />')) + '</strong></div>';
	strHtml += '</div>';
	strHtml += '<img src="../media/global/transparent.gif" width="250" height="1" alt="" />';
	strHtml += '</td>';
	strHtml += '</tr>';

	//Beaschreibung
	if (objCase.getElementsByTagName('description')[0].firstChild != null)
	{
		strHtml += '<tr>';
		strHtml += '<td colspan="3">';
		strHtml += '<h3>Beschreibung der Maßnahme</h3>';
		if (objCase.getElementsByTagName('description')[0].firstChild != null)
		{
			strHtml += '<div class="body-detail">' + addSearchMarks(objCase.getElementsByTagName('description')[0].firstChild.nodeValue.replace(/\n/g, '<br />')) + '</div>';
		}
		strHtml += '</td>';
		strHtml += '</tr>';
	}

	//Downloads
	if (objCase.getElementsByTagName('file').length > 0)
	{
		strHtml += '<tr>';
		strHtml += '<td colspan="3">';
		strHtml += '<h3>Fotos / Sonderberichte / Wirtschaftlichkeitsberichte</h3>';
		strHtml += '<div class="body-detail">';
		for (var i = 0; i < objCase.getElementsByTagName('file').length; i++)
		{
			strHtml += '<a href="../common/get_file.php?id=' + objCase.getElementsByTagName('file')[i].getAttribute('id') + '">' + objCase.getElementsByTagName('file')[i].firstChild.nodeValue + '</a><br />';
		}
		strHtml += '</div>';
		strHtml += '</td>';
		strHtml += '</tr>';
	}

	//Link alle Fallbeispiele
	strHtml += '<tr>';
	strHtml += '<td colspan="3">';
	strHtml += '<div class="body-detail" style="margin-top:10px">';
	strHtml += '<div><a href="#" onclick="sendSearchRequest(\'' + objCase.getElementsByTagName('company')[0].firstChild.nodeValue + '\'); window.scrollTo(0, 0); return false;">Alle Fallbeispiele dieses Betriebes anzeigen</a></div>';
	strHtml += '</td>';
	strHtml += '</tr>';
	strHtml += '</table>';

	document.getElementById('search_details').innerHTML = strHtml;
}

function addSearchMarks(in_strText)
{
	var strText = in_strText;
	if (document.forms['frm_search'].elements['catchwords'] != null && document.forms['frm_search'].elements['catchwords'].value != '')
	{
		var arrCatchwords = document.forms['frm_search'].elements['catchwords'].value.split(' ');
		for (var i = 0; i < arrCatchwords.length; i++)
		{
			strText = strText.replace(eval('/(' + arrCatchwords[i].replace(/\+|-|"/g, '') + ')/i'), '<span class="text-search-hits">$1</span>')
		}
	}
	return strText;
}