
/*****************************************************************************
 * maps stuff
 *****************************************************************************/



// initialization state
var gm_initDone = 0; // 1=success, 2=error

// objects used
var gm_map;
var gm_allMarkers= new Array;
var gm_markerInView = 0;

function gm_panToNext()
{	
	// function pans the map to the next marker in gm_allMarkers, loops on end
	// this function may only be called if gm_initPan() has succeeded
	
	gm_markerInView = gm_markerInView+1;
	if( gm_markerInView >= gm_allAdr.length ) gm_markerInView = 0;
	
	if( gm_allMarkers[gm_markerInView] )
	{
		gm_map.panTo(gm_allMarkers[gm_markerInView].getPoint())
		gm_allMarkers[gm_markerInView].openInfoWindowHtml(gm_allDescr[gm_markerInView]);
	}
	else
	{
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng
		(
			gm_allAdr[gm_markerInView],
			function(point)
			{
				if( !point )
				{
					alert(gm_allAdr[gm_markerInView] + ' nicht gefunden.');
				}
				else
				{
					gm_map.panTo(point);
					gm_allMarkers[gm_markerInView] = new GMarker(point);
					gm_allMarkers[gm_markerInView].myDescr = gm_allDescr[gm_markerInView];
					GEvent.addListener(gm_allMarkers[gm_markerInView], 'click', function() {
						this.openInfoWindowHtml(this.myDescr);
					});
					gm_map.addOverlay(gm_allMarkers[gm_markerInView]);
					gm_allMarkers[gm_markerInView].openInfoWindowHtml(gm_allDescr[gm_markerInView]);
				}
			}
		);						
	}
}



function gm_initPan(quality)
{
	// init the pan to one of the three resolution qualities in gm_initAdr
	
	// create a async. geocode
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng
	(
		gm_initAdr[quality],
		function(point)
		{
			// async geocoder event:
			if( !point )
			{
				// geocoding failed ...
				if( quality >= 2 || gm_initAdr[quality+1]=='' )
				{
					// ... nothing found at all
					$('#wisy_mapHeadline').hide();
					$('#wisy_map').hide();
					gm_initDone = 2; // error
					return;
				}
				else if( quality == 0 )
				{
					// ... try again with fallback #1
					window.setTimeout(function() {gm_initPan(1);}, 500);
					return;
				}
				else if( quality == 1 )
				{
					// ... try again with fallback #2
					window.setTimeout(function() {gm_initPan(2);}, 500);
					return;
				}
			}
			else
			{
				// geocoding succeeded!

				// center the map:
				// we move the center a little bit down to avoid a scrolling when the info window opens;
				// the offset is fine for "street view" (zoom 15)
				var center = new GLatLng(point.lat()+0.0016, point.lng()); 
				gm_map.setCenter(center, gm_initZoom[quality]);
				
				// add a marker at the calculated point
				gm_allMarkers[0] = new GMarker(point);
				gm_allMarkers[0].myDescr = gm_allDescr[0];
				GEvent.addListener(gm_allMarkers[0], 'click', function() {
					this.openInfoWindowHtml(this.myDescr);
				});
				gm_map.addOverlay(gm_allMarkers[0]);
			}

			// done - success
			gm_initDone = 1;
		}
	);
}


// maps inititalization

$.fn.initWisyMap = function()
{
	// init the gm_map and all needed objects, this function is called after the
	// page has loaded completely

	if( typeof(GBrowserIsCompatible) == 'undefined' )
	{
		return;
	}
		
	if( !GBrowserIsCompatible() )
	{
		return;
	}
	
	$(window).unload( function () { GUnload(); } );

	gm_map = new GMap2(document.getElementById("wisy_map"));

	gm_map.addMapType(G_PHYSICAL_MAP);
    gm_map.addControl(new GMenuMapTypeControl());
    gm_map.addControl(new GLargeMapControl());
	
	gm_initPan(0);	
	
	return;
}

function gm_mapHere()
{
	document.write('<h2 id="wisy_mapHeadline">Kursort und Umgebung</h2><div id="wisy_map"></div>');
}



/*****************************************************************************
 * autocomplete stuff
 *****************************************************************************/

function clickAutocompleteHelp(tag_help, tag_name_encoded)
{
	location.href = 'g' + tag_help + '?ie=UTF-8&q=' + tag_name_encoded;
}

function formatItem(row)
{
	var tag_name = row[0];
	var tag_type = row[1];
	var tag_help = row[2];
	
	/* see also (***) in the PHP part */
	var row_class   = 'ac_normal';
	var row_prefix  = '';
	var row_postfix = '';
	
	/* base type */
	     if( tag_type &   1 ) { row_class = "ac_abschluss";            row_postfix = ' <span class="ac_tag_type">(Abschluss)</span>'; }
	else if( tag_type &   2 ) { row_class = "ac_foerderung";           row_postfix = ' <span class="ac_tag_type">(F&ouml;rderung)</span>'; }
	else if( tag_type &   4 ) { row_class = "ac_qualitaetszertifikat"; row_postfix = ' <span class="ac_tag_type">(Qualit&auml;tszertifikat)</span>'; }
	else if( tag_type &   8 ) { row_class = "ac_zielgruppe";           row_postfix = ' <span class="ac_tag_type">(Zielgruppe)</span>'; }
	else if( tag_type &  16 ) { row_class = "ac_abschlussart";         row_postfix = ' <span class="ac_tag_type">(Abschlussart)</span>'; }
	else if( tag_type & 128 ) { row_class = "ac_thema";                row_postfix = ' <span class="ac_tag_type">(Thema)</span>'; }
	else if( tag_type & 256 ) { row_class = "ac_anbieter";             row_postfix = ' <span class="ac_tag_type">(Anbieter)</span>'; }
	else if( tag_type & 512 ) { row_class = "ac_ort";                  row_postfix = ' <span class="ac_tag_type">(Ort)</span>'; }

	/* additional flags */
	if( tag_type & 0x10000000 )
	{
		row_prefix = '&nbsp; &nbsp; &nbsp; &nbsp; &#8594; ';
		row_class += " ac_indent";
	}	
	else if( tag_type & 0x20000000 )
	{
		row_prefix = 'Meinten Sie: ';
	}
	
	/* help link */
	if( tag_help != 0 )
	{
		row_postfix +=
		 " <a class=\"wisy_help\" href=\"\" onclick=\"clickAutocompleteHelp(" + tag_help + ", '" +encodeURIComponent(tag_name)+ "');return false;\">&nbsp;i&nbsp;</a>";
	}
	
	return '<span class="'+row_class+'">' + row_prefix + tag_name + row_postfix + '</span>';
}

function formatResult(row) {
	return row[0].replace(/(<.+?>)/gi, '');
}

function initAutocomplete()
{
	$(".ac_keyword").autocomplete('autosuggest',
	{
		width: '40%',
		multiple: true,
		matchContains: true,
		matchSubset: false, /* andernfalls wird aus den bisherigen Anfragen versucht eine Liste herzustellen; dies schlaegt dann aber bei unseren Verweisen fehl */
		formatItem: formatItem,
		formatResult: formatResult,
		max: 512,
		selectFirst: false
	});
}



/*****************************************************************************
 * advanced search stuff
 *****************************************************************************/

function advEmbeddingViaAjaxDone()
{
	initAutocomplete();

	// fade from normal to adv
	$("#wisy_searcharea").hide('slow'); 
	$("#advEmbedded").show('slow');
	
	// remove the loading indicatiot
	$("#wisy_searchinput").removeClass('ac_loading');
	
	// ajaxify  the "cancel" button
	$("#adv_cancel").click(function()
	{
		// fade from adv to normal
		$("#wisy_searcharea").show('slow');
		$("#advEmbedded").hide('slow', function(){ $("#advEmbedded").remove() });
		
		// done
		return false;
	});
}

function advEmbedViaAjax()
{
	// add the loading indicator
	$("#wisy_searchinput").addClass('ac_loading');
	
	// create and load the advanced options
	var q = $("#wisy_searchinput").val(); // for some reasons, q is UTF-8 encoded, so we use this charset as ie= below
	var justnow = new Date();
	var rnd = justnow.getTime();
	
	$("#wisy_searcharea").after('<div id="advEmbedded" style="display: none;"></div>');
	$("#advEmbedded").load('advanced?ajax=1&ie=UTF-8&rnd='+rnd+'&q='+encodeURIComponent(q), advEmbeddingViaAjaxDone);
	return false;
}


/*****************************************************************************
 * index pagination stuff
 *****************************************************************************/

function paginateViaAjaxDone()
{
	$("#wisy_searchinput").removeClass('ac_loading');
	initPaginateViaAjax();
}

function paginateViaAjax(theLink)
{
	$("#wisy_searchinput").addClass('ac_loading');
	$("#wisy_resultarea").load(theLink.href + '&ajax=1', paginateViaAjaxDone);
}

function initPaginateViaAjax()
{
	$("span.wisy_paginate a").click(function(){paginateViaAjax(this);return false;});
	$("a.wisy_orderby").click(function(){paginateViaAjax(this);return false;});
}

/*****************************************************************************
 * dropdown stuff
 *****************************************************************************/

$.fn.dropdown = function()
{
	// needed only for IE6 dropdown menu
	$(this).hover(function(){
		$(this).addClass("hover");
		$('> .dir',this).addClass("open");
		$('ul:first',this).css('visibility', 'visible');
	},function(){
		$(this).removeClass("hover");
		$('.open',this).removeClass("open");
		$('ul:first',this).css('visibility', 'hidden');
	});

}


/*****************************************************************************
 * old edit stuff
 *****************************************************************************/

function ed(theAnchor)
{
	// remove focus -- do this first to avoid coming the new window into the background
	if( theAnchor.blur ) {
		theAnchor.blur();
	}

    // open new window;
    // no spaces in string, bug in function window.open()
    var w = window.open(theAnchor.href, theAnchor.target, 'width=610,height=580,resizable=yes,scrollbars=yes');
    
    // bring window to top
    if( !w.opener ) {
    	w.opener = self;
    }
    	
    if( w.focus != null ) {
    	w.focus();
    }
	
	// avoid standard hyperlink processing
    return false;
}

/*****************************************************************************
 * new edit stuff
 *****************************************************************************/

function editShowHide(jqObj, toShow, toHide)
{
	jqObj.parent().parent().find(toShow).show('fast');
	jqObj.parent().parent().find(toHide).hide();
}

function editFindDurchfRow(jqObj)
{
	var durchfRow = jqObj;
	var iterations = 0;
	while( 1 )
	{
		if( durchfRow.hasClass('editDurchfRow') )
			return durchfRow;
		durchfRow = durchfRow.parent();
		iterations++;
		if( iterations > 100 ) { alert('ERROR: editDurchfRow class not found ...'); return durchfRow; }
	}
}

function editDurchfLoeschen(jqObj)
{
	if( $('.editDurchfRow').size() == 1 )
	{
		alert("Diese Durchführung kann nicht gelöscht werden, da ein Kurs mindestens eine Durchführung haben muss.\n\nWenn Sie den Kurs komplett löschen möchten, verwenden Sie die Option \"Kurs löschen\" ganz unten auf dieser Seite.");
		return;
	}
	else if( confirm("Diese Durchführung löschen?") )
	{
		editFindDurchfRow(jqObj).remove();
	}
}
function editDurchfKopieren(jqObj)
{
	var durchfBase = editFindDurchfRow(jqObj);

	var clonedObj = durchfBase.clone();
	clonedObj.find('.hiddenId').val('0')

	durchfBase.after(clonedObj);	
}

function editKursLoeschen(jqObj)
{
	if( confirm("Wenn Sie einen Kurs löschen möchten, wird zunächst ein Sperrvermerk gesetzt; beim nächsten Index-Update wird der Kurs dann inkl. aller Durchführungen komplett gelöscht. Dieser Vorgang kann nicht rückgängig gemacht werden!\n\nDen kompletten Kurs inkl. ALLER Durchführungen löschen?") )
	{
		return true;
	}
	return false;
}

function editWeekdays(jqObj)
{
	// jqObj ist der Text; ein click hierauf soll das nebenliegende <input type=hidden> ändern
	var hiddenObj = jqObj.parent().find('input');
	if( hiddenObj.val() == '1' )
	{
		hiddenObj.val('0');
		jqObj.addClass   ('wisy_editweekdaysnorm');
		jqObj.removeClass('wisy_editweekdayssel');
	}
	else
	{
		hiddenObj.val('1');
		jqObj.addClass   ('wisy_editweekdayssel');
		jqObj.removeClass('wisy_editweekdaysnorm');
	}
}

/*****************************************************************************
 * feedback stuff
 *****************************************************************************/

function ajaxFeedback(rating, descr)
{
	var url = 'feedback?url=' + encodeURIComponent(window.location) + '&rating=' + rating + '&descr=' + encodeURIComponent(descr);
	$.get(url);
}

function describeFeedback()
{
	var descr = $('#wisy_feedback_descr').val();
	descr = $.trim(descr);
	if( descr == '' )
	{
		alert('Bitte geben Sie zuerst Ihren Kommentar ein.');
	}
	else
	{
		$('#wisy_feedback_line2').html('<strong style="color: green;">Vielen Dank für Ihren Kommentar!</strong>');
		ajaxFeedback(0, descr); // Kommentar zur Bewertung hinzufügen; die Bewertung selbst (erster Parameter) wird an dieser Stelle ignoriert!
	}
}

function sendFeedback(rating)
{
	$('#wisy_feedback_yesno').html('&nbsp; &nbsp;<strong style="color: green;">Vielen Dank für Ihr Feedback!</strong>');
	
	if( rating == 0 )
	{
		$('#wisy_feedback_line1').after(
				'<p id="wisy_feedback_line2">'
			+		'Bitte schildern Sie uns noch kurz, warum diese Information nicht hilfreich war und was wir besser machen können:<br />'
				+	'<textarea id="wisy_feedback_descr" name="wisy_feedback_descr" rows="2" cols="20" style="width: 320px;"></textarea><br />'
				+	'<input type="submit" onclick="describeFeedback(); return false;" value="Kommentar senden" />'
			+	'</p>'
		);
		$('#wisy_feedback_descr').focus();
	}
	else 
	{
		$('#wisy_feedback_line1').after(
				'<p id="wisy_feedback_line2">'
			+		'Bitte schildern Sie uns kurz, was hilfreich war, damit wir Bew&auml;hrtes bewahren und ausbauen:<br />'
				+	'<textarea id="wisy_feedback_descr" name="wisy_feedback_descr" rows="2" cols="20" style="width: 320px;"></textarea><br />'
				+	'<input type="submit" onclick="describeFeedback(); return false;" value="Kommentar senden" />'
			+	'</p>'
		);
		$('#wisy_feedback_descr').focus();
	}
	
	ajaxFeedback(rating, '');
}

function initFeedback()
{
	$('.wisy_allow_feedback').after(
			'<p id="wisy_feedback_line1" class="noprint"><b>War diese Information hilfreich?</b> '
		+		'<span id="wisy_feedback_yesno"><a href="javascript:sendFeedback(1)">Ja</a> - <a href="javascript:sendFeedback(0)">Nein</a></span>'
		+	'</p>'
	);
}


/*****************************************************************************
 * the simple editor functions
 *****************************************************************************/

// Surrounds the selected text with text1 and text2.
function surroundText(text1, text2, textarea)
{
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		// Can a text range be created?
		var caretPos = textarea.caretPos, temp_length = caretPos.text.length;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;

		if (temp_length == 0)
		{
			caretPos.moveStart("character", -text2.length);
			caretPos.moveEnd("character", -text2.length);
			caretPos.select();
		}
		else
		{
			textarea.focus(caretPos);
		}
	}
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		// Mozilla text range wrap.
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	else
	{
		// Just put them on the end
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
}

function add_chars(chars1, chars2)
{
	surroundText(chars1, chars2, document.forms.kurs.beschreibung);
}

function add_button(title, tooltip, style, onclck)
{
	return     '<td>' 
			 + 		'<input title="'+tooltip+'" type="button" value="'+title+'" style="'+style+'" onclick="'+onclck+'" />'
			 + '</td>';
}

function renderEditorToolbar()
{
	toolbar_html = '<table border="0" cellspacing="0" cellpadding="1"><tr>';
		toolbar_html += add_button("'''Fett'''", 'Markieren Sie den zu fettenden Text und klicken Sie dann diese Schaltfläche', 'width:66px; font-weight:bold;', "add_chars('\\\'\\\'\\\'', '\\\'\\\'\\\''); return false;");
		toolbar_html += add_button("''Kursiv''", 'Markieren Sie den kursiv darzustellenden Text und klicken Sie dann diese Schaltfläche', 'width:66px; font-style:italic;', "add_chars('\\\'\\\'', '\\\'\\\''); return false;");
		toolbar_html += add_button("[[Verweis]]", 'Markieren Sie den Text, den Sie als Verweis verwenden möchten, und klicken Sie dann diese Schaltflächen', 'width:80px; ', "add_chars('[[http://verweis.com|', ']]'); return false;");
	toolbar_html += '</tr></table>';
	document.write(toolbar_html);
}


/*****************************************************************************
 * main entry point
 *****************************************************************************/

$().ready(function()
{
	// init autocomplete
	initAutocomplete();

	// init dropdown
	if ($.browser.msie && $.browser.version == '6.0') {
    	$("ul.dropdown li").dropdown();
	}	
	
	// handle "advanced search" via ajax
	$("#wisy_advlink").click(advEmbedViaAjax);
	
	// handle "paginate" via ajax
	// currently, we NO NOT do so as this fails the "back button" to work correctly, eg. the order is not set.
	// we should add the parameter behind the hash "#ordere=" or sth. like that.
	// initPaginateViaAjax();
	
	// init feedback stuff
	initFeedback();

	// init maps
	$("#wisy_map").initWisyMap();
});

