var abs_path = 'http://www.cinetirol.com/';

/* Multiheader */
var overlayGroups = new Array();
var listMax = 5;
var startvideo;
var ajaxUrl = "";
var polygonSelected = false;
var acData;
var acRequests = 0;
var calcRoute;
var ids;
// aktuelles element im multiheader location service
var locMHCurr = false;

var animation = false;

var random = false;

// parent-element für filterfunktion karte
var par;

/* Routenplaner */
function toggleRoutplaner(coords, name) {
	var latlng = coords.split(',');
	map.checkResize();
	map.setCenter(new GLatLng(latlng[0], latlng[1]));
	$('#xxlTo').val(name);
	$('#xxlRouteForm').show();
}

function getDirections(fromAddress, toAddress, locale) {
	directions = new GDirections(map, document.getElementById("xxlDirections"));
	
	GEvent.addListener(directions, "error", handleErrors);
	var highways = $('#xxlHighway').is(':checked') ? true : false;
	
	wp = new Array();
	wp.push($('#xxlFrom').val());
	$('.xxlVia').each(function(i, e) {
		wp.push($(e).val());
	});
	searchto = String($('#xxlTo').val() + ' tirol');
	wp.push(searchto);
	
	directions.loadFromWaypoints(wp, { "locale": locale, "avoidHighways": highways });
	
	$('#xxlDirections').show();
	$('#xxlError').html("");
}


function handleErrors(){
	if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		$('#xxlError').html(langData['unknownAdr'] + directions.getStatus().code);
	else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
		$('#xxlError').html(langData['serverError'] + directions.getStatus().code);
	else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
		$('#xxlError').html(langData['emptyRequest'] + directions.getStatus().code);
	else if (directions.getStatus().code == G_GEO_BAD_KEY)
		$('#xxlError').html(langData['badKey'] + directions.getStatus().code);
	else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
		$('#xxlError').html(langData['badRequest'] + directions.getStatus().code);
	else
		$('#xxlError').html(langData['unknownError']);
}

function jToggleHistory(id){
	$('#history' + id).slideToggle('slow');
	$('#historyPreview' + id).slideToggle('slow');
}

function setMapCheckboxes(){
	$('#xxlMapCheck').children('input').attr('checked', 'checked');
}

// cycle multiheader initialisieren
function initCycle(){
	$('.xxlHolder').cycle({
		fx:     'fade', 
		speed:  500, 
		timeout: 0,
		next:   '#xxlNext', 
		prev:   '#xxlPrev',
		before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
			if($('img', nextSlideElement).attr('longdesc')) {
				var longdesc = $('img', nextSlideElement).attr('longdesc');
				$('img', nextSlideElement)
					.attr('src', longdesc)
					.removeAttr('longdesc');
			}
		}
	});
}

function showVideo(videolink){
	if (videolink == undefined || videolink == '') {
		videourl = videourl.replace(/<div id="xxlHeaderVideo">/g,"");
		videourl = videourl.replace(/<\/div>/g,"");
	} else {
		if ($("#xxlHeaderVideo").length == 0) {
			$('#xxlMultiHeader').prepend('<div id="xxlHeaderVideo" style="display: none;"></div>');
		}
		if (videolink.search(/youtube/) != -1) {
			iframeurl = videolink.replace(/\/v\//, "/embed/") + '?wmode=transparent&controls=0&showinfo=0&rel=0';
		} else if (videolink.search(/vimeo/) != -1) {
			vimeoid = videolink.split("=");
			iframeurl = "http://player.vimeo.com/video/" + vimeoid[1];
		}
		videourl = '<a onclick="showSlideshow()" id="xxlCloseVideo"></a>';
		videourl += '<iframe id="youtubeEmbed" width="750" height="360" src="' + iframeurl + '?wmode=transparent&controls=0&showinfo=0&rel=0" frameborder="0"></iframe>';
	}
	$('.xxlHolder').hide();
	$('#xxlPrev').hide();
	$('#xxlNext').hide();
	$('#xxlRouteForm').hide();
	$("#xxlHeaderVideo").html(videourl);
	$('#xxlHeaderVideo').show();
	$('.xxlHolder').cycle('pause');
	$('#xxlMapSelector').hide();	
}

function showSlideshow(){
	if ($("#xxlExtInfoWindow").length > 0) {
		$('#xxlExtInfoWindow').hide();
	}
	$('#xxlHeaderVideo').hide();
	$('#xxlHeaderVideo').html('');
	$('#xxlRouteForm').hide();
	$('.xxlHolder').show();
	$('.xxlHolder').cycle('resume');
	$('#xxlMap').removeClass('visible');
	$('#xxlMapSelector').hide();
	$('#xxlNext').show();
	$('#xxlPrev').show();
}	

function showMap(){
	$('#xxlHeaderVideo').hide();
	$('#xxlHeaderVideo').html("");
	$('.xxlHolder').hide();
	$('#xxlPrev').hide();
	$('#xxlNext').hide();
	$('#xxlMap').addClass('visible');
	$('#xxlMapSelector').show();
	setMapCheckboxes();
	if(typeof showAllKML == "function") {
		showAllKML();
	}
}

/* Videochannel */
function filterTopics() {
	var selected = Array();
	
	$('.videotopic:checked').each(function() {
		selectedtopic = $(this).attr('id').substr(6);
		selected.push(selectedtopic);
	});
	
	if (selected.length > 0) {
		$('.xxlVideoHolder').each(function() {
			thistopics = $(this).find('.topics').val().split(',');
			showholder = false;
			for(i=0;i<thistopics.length;i++) {
				if (!$.inArray(thistopics[i], selected)) {
					showholder = true;
				}
			}
			if (showholder) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	} else {
		$('.xxlVideoHolder').each(function() {
			$(this).show();
		});
	}
}

function searchKeywords() {
	searchval = $('#videochannel_vt').val().toLowerCase();	
	
	if (searchval.length > 0) {
		$('.xxlVideoHolder').each(function() {
			thiskeywords = $(this).find('.keywords').val().toLowerCase();
			if (thiskeywords.indexOf(searchval) != -1) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	} else {
		$('.xxlVideoHolder').each(function() {
			$(this).show();
		});
	}
}

function sortVideos(sortby) {	
	var sortlist = $('#xxlVideochannelList');
	var listitems = sortlist.children('.xxlVideoHolder').get();
	
	listitems.sort(function(a, b) {
		var compA = $(a).find('.' + sortby).val().toLowerCase();
		var compB = $(b).find('.' + sortby).val().toLowerCase();
		if (sortby == 'title') {
			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		} else {
			return compB - compA;
		}
	});	
		
	$.each(listitems, function(idx, itm) { sortlist.append(itm); });
}

function mapVideoMarkerClick(url) {
	showVideo(url);
}

/* Formular Überprüfung */
function xxlCheckEmptyForm() {
	if ($('#xxlImage1').val().length > 0 && $('#xxlImageRights').is(':checked') == false) {
		alert ('Bitte bestätigen Sie, dass Sie die Bildrechte an diesem Foto besitzen');
		return false;
	}
    // if ($('#publish').is(':checked') == false) {
		// alert ('Sie müssen das Veröffentlichen akzeptieren');
        // return false;
    // }
	if (xxlCheckEmpty ($("#location_title"), 'Bitte geben Sie den Name des Drehortes ein') == false) {
        return false;
    }
    if (xxlCheckEmpty ($("#kontakt"), 'Bitte geben Sie Ihren Namen ein') == false) {
        return false;
    }
    if (xxlCheckEmpty ($("#tel"), 'Bitte geben Sie Ihre Telefonnummer an') == false) {
        return false;
    }
    if (xxlCheckEmail ($("#email"), 'Bitte gib eine gültige E-Mail-Adresse ein') == false) {
        return false;
    }
}
function xxlCheckEmpty(feld, message) {
	// jQuery object
	if (feld instanceof $) {
		var content = feld.val();
	// DOM object
	} else {
		var content = feld.value;
	}
	if (content == '') {
		alert (message);
		feld.focus();
		return false;
	}
	return true;
}
function xxlCheckEmail(feld, message) {
	// jQuery object
	if (feld instanceof $) {
		var content = feld.val();
	// DOM object
	} else {
		var content = feld.value;
	}
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(content) == false) {
		alert (message);
		feld.focus();
		return false;
	}
	return true;
}


/* Gmap Funktionen */
function highlightMarker(i) {
	markerdiv = $('#mtgt_unnamed_' + i);
	z = markerdiv.css('z-index');
	markerdiv.css('z-index', (z*1));
	thismarker = map_overlayGroups['marker'][i];
    GEvent.trigger(thismarker, "mouseover");
}

function unhighlightMarker(i) {
	markerdiv = $('#mtgt_unnamed_' + i);
	z = markerdiv.css('z-index');
	markerdiv.css('z-index', (z*-1));
	thismarker = map_overlayGroups['marker'][i];
    GEvent.trigger(thismarker, "mouseout");
}

function mapMarkerClick(marker, url) {
	window.location = url;
}

function mapMarkerOver(marker, url) {
	marker.setImage(marker.high_icon.image);	
	map.openExtInfoWindow(
		marker.point,
		"xxlExtInfoWindow",
		marker.html,
		{beakOffset: 3}
	);
}

function mapMarkerOut(marker, url) {
	marker.setImage(marker.icon.image);
}

var polyclicked = false;

function highlightPoly(polynumber) {
	if (typeof(window['polynumber_' + polynumber]) != "undefined") {
		polyclicked = false;
		polygmapid = eval('polynumber_' + polynumber);
		high_polygon = map_overlayGroups['polygones'][polygmapid];
		GEvent.trigger(high_polygon, "mouseover");
	}
}

function unHighlightPoly(polynumber) {
	if (typeof(window['polynumber_' + polynumber]) != "undefined") {
		polygmapid = eval('polynumber_' + polynumber);
		high_polygon = map_overlayGroups['polygones'][polygmapid];
		GEvent.trigger(high_polygon, "mouseout");
	}
}

function detailRoutePlaner() {
	$('#xxlDirections').remove();
	$('#xxlError').remove();
	
	switch($('#xxlType').val()) {
		case 'ausflug':
			$.ajax({
				url: abs_path + 'ajax.php',
				type: 'POST',
				data: '_action=invGeocoder&_c=' + $('#xxlTo').val(),
				dataType: 'json',
				success: function(data) {
					showMap();
					$('#content_detail_left').prepend('<div id="xxlDirections"></div>');
					$('#content_detail_left').prepend('<div id="xxlError"></div>');
					//$('#content').hide();
					$('#xxlTo').val(data.results[0].formatted_address);
					$('#xxlType').val('address');
					getDirections($('#xxlLocale').val());
				}
			});
			break;
		case 'address':
			showMap();
			$('#content_detail_left').prepend('<div id="xxlDirections"></div>');
			$('#content_detail_left').prepend('<div id="xxlError"></div>');
			//$('#content').hide();
			$('#xxlType').val('address');
			getDirections($('#xxlLocale').val());
			$('#xxlDirections').css('padding-left', '30px');
			$('#xxlError').css('padding-left', '30px');
			break;	
	}
	return false;
}

function initFancyboxGallery() {
	$("a[rel=tirolat]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition'	 	: 'none'
	});
}

/**
 * Blendet die Elemente der Seite ein
 * Setzt aktive Jumplist
 * @param {integer} page Aktive Seite
 */
function toggleListEntries(page) {
	if(typeof page == "string") {
		page = parseInt(page);
	}
	
	var start = ((page-1) * listMax);
	var end = start + listMax;
	var pageIDs = new Array();
	
	$('.xxlListbox').hide();
	// location archive
	if (document.getElementById('xxlLocationList')) {
		toggleListEntriesLocation (start, end);
	// normale liste -> img longdesc in src setzen
	} else {
		$('.xxlListbox:visible img[longdesc*="media"]').each(function() {
			$(this).attr('src', $(this).attr('longdesc'));
			$(this).removeAttr('longdesc');
		});
		$('.xxlListbox').slice(start, end).show();
	}

	$('.xxlJumplistPageActive').removeClass('xxlJumplistPageActive');
	$('.xxlJumpListEntry').each(function() {
		if($(this).html() == page) {
			$(this).addClass('xxlJumplistPageActive');
		}
	});

	var limit = 5;
	var len = $('.xxlJumplist:first .xxlJumpListEntry').length;
	
	$('.xxlJumpListEntryPrev').hide();
	$('.xxlJumpListEntryNext').hide();
	
	if((page - limit) > 1) {
		$('.xxlJumpListEntryPrev').show();
	}
	if((page + limit) < (len + 1)) {
		$('.xxlJumpListEntryNext').show();
	}
	if((page + limit) == len) {
		$('.xxlJumpListEntryNext').hide();
	}

	if(page < limit) {
		limit = (limit * 2) - page + 1;
	} else if(page == limit) {
		limit++;
	} else if((page + limit) > len) {
		limit = (limit * 2) - (len - page) - 1;
	}
	
	$('.xxlJumpListEntry').each(function() {
		$(this).parent().hide();
	});
	
	for(var i = (page - limit); (i < (page + limit) && (i < (len + 1))); i++) {
		if(i > 0) {
			$('.xxlJumpListEntry' + i).show();
		}
		if($('.xxlJumpListEntry', $('.xxlJumpListEntry' + i)).html() == page) {
			$('.xxlJumpListEntry', $('.xxlJumpListEntry' + i)).addClass('xxlJumplistPageActive');
		}
	}
}

/**
 * Holt Datensätze für Location Archive
 * @param {integer} start Erster Eintrag
 * @param {integer} end Letzter Eintrag
 */
function toggleListEntriesLocation (start, end) {
	if(ids.length == 0) {
		return;
	}
	
	// 3-teiliger header -> noch kein location-multiheader
	if ($('#xxlMultiHeader').hasClass('xxlCatMultiHeader')) {
		// multiheader erzeugen
		$('#xxlMultiHeader').replaceWith('<div id="xxlMultiHeader"><div id="xxlHolderShow"><ul class="xxlHolder"></ul><span id="xxlPrev"> </span><span id="xxlNext"> </span></div></div><ul id="xxlMultiHeaderTrash"></ul>');
	} else {
		// elemente aus multiheader in zwischenablage verschieben
		$('#xxlMultiHeader li').appendTo($('#xxlMultiHeaderTrash'));
	}

	var locids = '';
	
	// ende der liste
	if (end > $('#xxlLocationList .xxlListbox').length) {
		end = $('#xxlLocationList .xxlListbox').length;
	}
	
	// elemente auslesen
	for (var i=start; i<end; i++) {
		var currElem = $('#xxlLocationList .xxlListbox:eq(' + i + ')');
		// noch kein HTML-inhalt
		if (currElem.is('a')) {
			// leere li im header anlegen
			$('#xxlMultiHeader ul.xxlHolder').append('<li id="xxlPic' + currElem.data('id') + '"></li>');
			// id für JSON suche speichern
			locids += ',' + currElem.data('id');
		} else {
			// element einblenden
			currElem.show();
			// bestehende elemente in multiheader verschieben
			$('#xxlMultiHeaderTrash li#xxlPic' + currElem.data('id')).appendTo($('#xxlMultiHeader ul.xxlHolder'));
		}
	}
	
	// einträge zum nachladen
	if (locids.length > 0) {
		$.fancybox.showActivity();
		locids	= locids.substring(1);
		$.getJSON ('/scms/detail.php', {
			'template' : 'ct11_l7_ajax',
			'ids' : locids
		}, function (data) {
			for (var key in data) {
				// content
				var currHTML	= data[key].listElm;
				// übersetzungen tauschen
				currHTML	= currHTML.replace (/tistext\(([^)]+)\)/g, '$1');
				// daten aus a lesen
				var currElm		= {
					'_href' : $('#xxlListbox' + key).attr('href'),
					'_class' : $('#xxlListbox' + key).attr('class')
				};
			
				// a durch komplettes div ersetzen
				$('#xxlListbox' + key).replaceWith(currHTML);
				
				// alle links vergeben
				$('#xxlListbox' + key + ' a.xxlLoadLocDetail').attr('href', currElm._href);
				
				// data und klasse vergeben
				$('#xxlListbox' + key)
					.attr('class', currElm._class)
					.data('id', key)
					.show();
					
				// bild in multiheader schreiben
				currHTML	= data[key].headerImg;
				// src durch longdesc ersetzen (zum nachladen)
				currHTML	= currHTML.replace (/\ssrc(="[^"]+")/, ' longdesc$1');
				$('#xxlMultiHeader li#xxlPic' + key).html(currHTML);
				$('#xxlMultiHeader li#xxlPic' + key + ' a').attr('href', currElm._href);

			}
			$.fancybox.hideActivity();
			initCycle();
		})
	} else {
		initCycle();
	}
}

function initJumplist() {
	var len = $('.xxlListbox').length;
	var pages = Math.ceil(len / listMax);
	var listString = '';
	
	if(pages > 1) {
		for(var i = 1; i <= pages; i++) {
			listString = listString + '<span class="xxlJumpListEntry' + i + '"><a href="javascript:void(0);" class="xxlJumpListEntry">' + i + "</a>";
			if(i < pages) {
				listString = listString + " / ";
			}
			listString = listString + '</span>';
		}
		listString = langData['page'] + ' <span class="xxlJumpListEntryPrev">...</span>' + listString + '<span class="xxlJumpListEntryNext">...</span>';
	} else {
		listString = "";
	}

	$('.xxlJumplist').each(function() {
		$(this).html(listString);
	});
	
	$('.xxlJumpListEntry').unbind('click');
	$('.xxlJumpListEntry').click(function() {
		toggleListEntries($(this).html());
		return false;
	});
	
	toggleListEntries(1);
	
	var contentTop = $('#xxlContent').position();
	contentTop = contentTop.top;
}

/**
 *	AjaxSearch
 *	Bei Erfolg wird das Formular per AJAX abgeschickt, daher muss ein verstecktes Feld _load vorhanden sein, das die entsprechende AJAX-Funktion spezifiziert
 *
 *	@param targetID HTML-ID der Ergebnissliste
 *	@param formID HTML-ID des Formulars
 */
function xxlAjaxSearch(targetID, formID) {
	$.ajax({
		type: "POST",
		url: abs_path + 'ajax.php',
		data: $('#' + formID).serialize(),
		success: function (data) {
			$('#' + targetID).html(data);
		}
	});
	return false;
}

/**
 *	Formular Location hinzufügen
 *	Bei Erfolg wird das Formular per AJAX abgeschickt, daher muss ein verstecktes Feld _load vorhanden sein, das die entsprechende AJAX-Funktion spezifiziert
 *
 *	@param targetID HTML-ID der Ergebnissliste
 *	@param formID HTML-ID des Formulars
 */
function xxlAjaxFormAddLocation(targetID, formID) {
	$.ajax({
		type: "POST",
		url: abs_path + 'ajax.php',
		data: $('#' + formID).serialize(),
		success: function (data) {
			$('#' + targetID).html(data);
		}
	});
	return false;
}

/**
 *  im Kalender nur eingetragene Termine wählbar machen
**/
function selectabledays(date){
	var i=0;
	for(i=0;i<startdate.length;i++) {
		var temp = new Date(startdate[i]);
		if(date.getDate() == temp.getDate() && date.getMonth() == temp.getMonth() && date.getFullYear() == temp.getFullYear()){
			return [true, "xxlBold", title[i]];
		}
	}
	return [false];
}

function smallscreen() {
	if(document.documentElement.clientWidth <= 1024) {
		// $('#xxlTirolLogo').css("margin","0px");
		$('body').css("background","#c3d4ce");
	}
}

/**
 *  Menü anpassen
 *  jQuery holt sich die Breite des Hauptmenüpunktes und setzt diesen als Breite bei den Untermenüpunkten
**/
function fixmenu() {
	for(i=2;i<=7;i++){
		var subi = i;
		var totalwidth = $('#xxlLi'+i).width();
		// console.log('#xxlLi'+i + ': ' + totalwidth);
		totalwidth = totalwidth + 50; // Width()-Berechnung basiert auf die normale Schrift (ohne Cufon) und deshalb wird der Wert um den Faktor 1.308 verkleinert
		// console.log('#xxlLi'+i + ': ' + totalwidth);
		subi--;
		$('#xxlSubUl'+subi).width(totalwidth);
	}
}

function xxlOffsetInit() {
	if($("#xxlMap").length>0) {
		$("#xxlMap").css("position", "relative");
		$("#xxlMap").css("top", "0");
		xxlMenuOffset = $("#xxlMap").offset().top;

		$(window).scroll(xxlOffset);
		xxlOffset();
	}
}

function xxlOffset() {
	// scroll-abstand von oben
	var winScroll = $(window).scrollTop();
	// unterhalb der navigation
	if (winScroll > xxlMenuOffset) {
		$("#xxlMap").css("position", "fixed");
		$("#xxlMap").css("top", "0px");
	} else {
		$("#xxlMap").css("position", "relative");
	}
}

/**
 *	Location-Archiv "Multiheader" (Übersicht) initialisieren
 */
function initLocationMultiheader() {
	$('.xxlCatMultiHeader ul li')
		.unbind('mouseenter')
		.unbind('click');
	
	$('.xxlCatMultiHeader ul li')
		.mouseenter(locMouseenter)
		.click(locLoadCat);
	
	$('.xxlCatMultiHeader ul').mouseleave(locMouseleave);
}

/**
 *	Kategorie, Multiheader laden, initialisieren
 */
function locLoadCat() {
	if(!$(this).is('.xxlLarge')) { // Nur Klick auf "große" Kategorien auswerten
		$('.xxlHolder').cycle('destroy');
		$('.xxlLarge #xxlHolderShow').remove();
		$('.xxlLarge > img').show();
		$('.xxlLarge #xxlPrev').remove();
		$('.xxlLarge #xxlNext').remove();
		
		initLocationMultiheader();
			
		$(this).mouseenter();
		
		return;
	}
	var element = $(this);
	$.fancybox.showActivity();
	
	$.ajax({
		url: abs_path + 'ajax.php',
		data: '_load=loadLocationCategory&_lang=' + lang + '&_headerID=' + $(this).data('pos').headerId + '&_catID=' + $(this).data('pos').catId,
		method: 'GET',
		dataType: 'json',
		success: function(data) {
			$('.xxlCatMultiHeader ul li')
				.unbind('mouseenter')
				.unbind('click');
			$('.xxlMed').click(locLoadCat);
			$('.xxlCatMultiHeader ul')
				.unbind('mouseleave');

			$.fancybox.hideActivity();
			
			var id = element.attr('id');
			$('#' + id + ' > img').hide();
			element.append(data.slideshow);

			// filterblock zu gewähltem header öffnen
			var id = $('a', $('.xxlFilterBlockCatTitle:eq(' + element.index() + ')')).attr('href').replace(/.*'([0-9]+)'.*/, "$1");
			
			if(!$('#xxlFilterBlock' + id + ' .xxlFilterOptions').is(':visible')) {
				toggleFilterBlock(id);
			}
			
			//eval($('a', $('.xxlFilterBlockCatTitle:eq(' + element.index() + ')')).attr('href').replace('javascript:', ''));
			initCycle();
		}
	});
}

/**
 *	Animiert den geteilten Header im Location Archiv
 *	Beim Wechsel zwischen Headerbildern
 */
function locMouseenter() {
	// animation läuft oder aktuelles element
	if(animation) {
		return;
	}
	// bereits ausgeklappt
	if ($(this).hasClass('xxlLarge')) {
		return;
	}
	
	animation = true;
	
	var animSpeed	= 200;
	
	window.setTimeout(function() { // deadlock vermeiden
		animation = false;
	}, animSpeed+50);
	
	// text ausblenden
	$('.xxlCatText').hide();
	
	for (var i=0; i<3; i++) {
		// aktuelles element -> vergrößern
		if (i == $(this).index()) {
			$(this).addClass('xxlLarge');
			$(this).removeClass('xxlMed');
			// text des aktuellen elements einblenden
			$(this).find('.xxlCatText').show();
			// li verbreitern
			$(this).animate({
				width: '656px'
			}, animSpeed);
			// bild zentrieren
			$(this).find('img').animate({
				marginLeft: '0px'
			}, animSpeed, function () {
				// nächste animation erlauben
				animation = false;
			});
		// andere elemente verkleinern
		} else {
			var currElem	= $('#xxlLocCat' + i);
			currElem.removeClass('xxlLarge');
			currElem.addClass('xxlMed');
			currElem.animate({
				width: '45px'
			}, animSpeed);
			currElem.find('img').animate({
				marginLeft: '-' + currElem.data('pos').posSmall + 'px'
			}, animSpeed);
		}
	}
}
function locMouseleave() {
	if(animation) {
		return;
	}
	animation = true;
	
	var animSpeed	= 200;
	
	window.setTimeout(function() { // deadlock vermeiden
		animation = false;
	}, animSpeed+50);
	
	$('.xxlCatText').show();

	for (var i=0; i<3; i++) {
		var currElem	= $('#xxlLocCat' + i);
		currElem.removeClass('xxlLarge');
		currElem.addClass('xxlMed');
		currElem.animate({
			width: '248px'
		}, animSpeed);
		// bild zentrieren
		currElem.find('img').animate({
			marginLeft: '-' + currElem.data('pos').posMed + 'px'
		}, animSpeed, function () {
			// nächste animation erlauben
			animation = false;
		});
	}
}

/**
 *	Filter Location Service initialisieren
 */
function initLocationFilter() {
	$('#vt_search').submit(function() {
		updateFilter();
		return false;
	});
	
	$('.xxlNewSearch').click(function() {
		$('#_vt').val('');
		$('#loc_filter input').removeAttr('checked');
		$('.xxlResetFilter').hide();
		
		if(
			!$('#xxlLocationList').is(':visible') || // ergebnisliste nicht sichtbar (einleitungstext)
			$('#xxlNoResults').is(':visible') || // keine suchergebnisse
			false
		) { // direkt zu liste
			window.location.hash = '';
			updateFilter();
		} else { // gehe zu einleitungstext
			$('#xxlLocationList').hide();
			$('.xxlLeftBox').show();
		}

		$('#xxlNoResults').hide();
		return false;
	});
		
	$.ajax({
		url: abs_path + 'ajax.php',
		data: '_load=initLocationFilter&_lang=' + lang,
		method: 'GET',
		dataType: 'json',
		success: function(data) {
			$('.xxlLocationFilterHolder').html('');
			if(data.cat) {
				for(var i = 0; i < data.cat.length; i++) {
					$('.xxlLocationFilterHolder').append(data.cat[i]);
				}
			}
			if(data.topic) {
				$('.xxlLocationFilterHolder').append(data.topic[0]);
			}
			if(data.reg) {
				$('.xxlLocationFilterHolder').append(data.reg[0]);
			}
			
			$('.xxlLocationFilterHolder input').change(updateFilter);
			
			$('#xxlLocationFilterWidget').show();
			$('.xxlFilterBlock').show();
			
			$('.xxlResetFilter a').click(function() {
				var parent = $(this).parent().parent();
				$('input', parent).removeAttr('checked');
				$(this).parent().hide();
				updateFilter();
				return false;
			});
			
			initRegMap();
			var hash = window.location.hash;
			setFilter(hash);
		}
	});
}

/**
 *	Regionsauswahl über Karte Location-Filter initialisieren
 */
function initRegMap() {
	$('#imgmap area')
		.mouseenter(function() {
			if($('#xxlBez' + $(this).attr('class')).hasClass('xxlBezHover')) {
				$('#xxlBez' + $(this).attr('class')).show();
			}
		})
		.mouseleave(function() {
			if($('#xxlBez' + $(this).attr('class')).hasClass('xxlBezHover')) {
				$('#xxlBez' + $(this).attr('class')).hide();
			}
		})
		.click(function() {
			switch($(this).attr('class')) {
				case 'LA':
					$('#regionLandeck')
						.attr('checked', 'checked')
						.change();
					break;
				case 'RE':
					$('#regionReutte').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'IM':
					$('#regionImst').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'IL':
					$('#regionInnsbruck-Land').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'I':
					$('#regionInnsbruck-Stadt').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'SZ':
					$('#regionSchwaz').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'KU':
					$('#regionKufstein').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'KB':
					$('#regionKitzb%C3%BChel').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
				case 'LZ':
					$('#regionLienz').attr('checked', 'checked');
					par = $('#xxlFilterBlockReg');
					updateFilter();
					break;
			}
		});
}

function setFilter(hash) {
	hash = hash.replace(/%25/g, "%");
	hash = hash.replace(/%7[cC]/g, "|");
	hash = hash.replace(/%5[eE]/g, "^");
	
	if((hash.length <= 6) || (hash.substr(0, 3) != '#F^')) {
		return;
	} else {
		hash = hash.replace('F^', '');
	}
	
	$('#xxlLocationList').show();
	$('.xxlTeaserText').hide();
	$('.xxlDetailComment').hide();
	$('.xxlLeftBox').hide();
	if($('#xxlLocationMerklistWidget .xxlCount').html() > 0) {
		$('#xxlLocationMerklistWidget').show();
	}
	hash = hash.substr(1).split('|');
	
	$('#_vt').val(hash[0]);
	
	var regs = hash[1].split(',');
	var len = regs.length;
	for(var i = 0; i < len; i++) {
		if(regs[i] == "") { // ich hasse die IEs
			continue;
		}
		regs[i] = regs[i].replace(/([^%]+)%.*/, "$1");
		var input = $('input[value*="' + regs[i] + '"]');
		input.attr('checked', 'checked');
		if(!input.is(':visible')) {
			input.parent().parent().show();
		}
	}
	
	for(var j = 2; j < 4; j++) {
		var ids = hash[j].split(',');
		len = ids.length;
		for(var i = 0; i < len; i++) {
			if(ids[i] == "") { // ich hasse die IEs
				continue;
			}
			var input = $('#loc_filter input[value="' + ids[i] + '"]');
			input.attr('checked', 'checked');
			if(!input.is(':visible')) {
				input.parent().parent().show();
			}
		}
	}
	
	updateFilter();
}

function updateFilter() {
	$.fancybox.showActivity();
	$('#xxlNoResults').hide();

	if(!$('#xxlLocationList').is(':visible')) {
		$('#xxlLocationList').show();
		$('.xxlTeaserText').hide();
		$('.xxlDetailComment').hide();
		$('.xxlLeftBox').hide();
		if($('#xxlLocationMerklistWidget .xxlCount').html() > 0) {
			$('#xxlLocationMerklistWidget').show();
		}
	}

	var data = $('#loc_filter').serialize();
	
	var parent = $(this).parent().parent().parent();
	if(typeof par == "object") {
		parent = par;
		par = 0;
	}
	
	if($('input:checked', parent).length) {
		$('.xxlResetFilter', parent).show();
	} else {
		$('.xxlResetFilter', parent).hide();
	}
	
	if($('#_vt').val()) {
		if(data) {
			data = data + '&_vt=' + $('#_vt').val();
		} else {
			data = '_vt=' + $('#_vt').val();
		}
	}
	
	var hash = {
		reg: [],
		topic: [],
		cat: []
	};
	
	$('#loc_filter input:checked').each(function() {
		if(($(this).attr('id').indexOf('region') != -1) || ($(this).attr('id').indexOf('reg') != -1)) { // region
			hash.reg.push($(this).val());
		} else if($(this).attr('id').indexOf('topic') != -1) { // topic
			hash.topic.push($(this).val());
		} else if(($(this).attr('id').indexOf('sonstiges') != -1) || ($(this).attr('id').indexOf('architektur') != -1) || ($(this).attr('id').indexOf('natur') != -1)) { // Kategorie
			hash.cat.push($(this).val());
		}
	});

	if(parent.length == 0) {
		if($('#_vt').val() != "") {
			data = data + '&exclude=vt';
		}
	} else {
		data = data + '&exclude=' + parent.attr('id');
	}

	data = '_load=filterList&_lang=' + lang + '&' + data;
	
	var hashStr = 'F^' + $('#_vt').val();

	for(var arr in hash) {
		hashStr = hashStr + "|" + hash[arr].join(",");
	}
	
	if(hashStr.length > 5) {
		window.location.hash = encodeURI(hashStr);
	} else {
		window.location.hash = '';
	}

	$.ajax({
		url: abs_path + "ajax.php",
		data: data,
		method: 'GET',
		dataType: 'JSON',
		success: function(data) {
			$.fancybox.hideActivity();
			$('.xxlLocationFilterHolder').html('');
			
			if(data.cat) {
				for(var i = 0; i < data.cat.length; i++) {
					$('.xxlLocationFilterHolder').append(data.cat[i]);
				}
			}
			if(data.topic) {
				$('.xxlLocationFilterHolder').append(data.topic[0]);
			}
			if(data.reg) {
				$('.xxlLocationFilterHolder').append(data.reg[0]);
			}

			$('.xxlLocationFilterHolder input')
				.unbind('change')
				.change(updateFilter);

			$('.xxlFilterBlock').show();
			
			$('.xxlLocationFilterHolder input:checked').each(function() {
				var parent = $(this).parent().parent();
				parent.show();
				$('.xxlResetFilter', parent.parent()).show();
			});
			
			$('.xxlResetFilter a')
				.unbind('click')
				.click(function() {
					var parent = $(this).parent().parent();
					$('input', parent).removeAttr('checked');
					$(this).parent().hide();
					updateFilter();
					return false;
				});
			
			ids = data.ids;
			filterListEntries();
			initJumplist();

			// karte + regionen unterhalb regionsauswahl anzeigen/ausblenden
			$('#xxlFilterBlockReg input').each(function() {
				var show = $(this).is(':checked');
				
				if($(this).val() == 'Landeck') { setMapRegOverlay(show, 'xxlBezLA'); }
				if($(this).val() == 'Reutte') { setMapRegOverlay(show, 'xxlBezRE'); }
				if($(this).val() == 'Imst') { setMapRegOverlay(show, 'xxlBezIM'); }
				if($(this).val() == 'Innsbruck-Land') { setMapRegOverlay(show, 'xxlBezIL'); }
				if($(this).val() == 'Innsbruck-Stadt') { setMapRegOverlay(show, 'xxlBezI'); }
				if($(this).val() == 'Schwaz') { setMapRegOverlay(show, 'xxlBezSZ'); }
				if($(this).val() == 'Kufstein') { setMapRegOverlay(show, 'xxlBezKU'); }
				if($(this).val() == 'Kitzb%C3%BChel') { setMapRegOverlay(show, 'xxlBezKB'); }
				if($(this).val() == 'Lienz') { setMapRegOverlay(show, 'xxlBezLZ'); }
			});
			
			initRegMap();
			
			if(data.count == 0) {
				$('#xxlNoResults').show();
			}
		},
		error: function (e1, e2, e3) {
			$.fancybox.hideActivity();
		}
	});
}

/**
 *	Bezirks-"Overlay" in Location-Filter anzeigen/verstecken + evtl. Hover-State entfernen
 */
function setMapRegOverlay(show, id) {
	if(show) {
		$('#' + id).show();
		$('#' + id).removeClass('xxlBezHover');
	} else {
		$('#' + id).hide();
		$('#' + id).addClass('xxlBezHover');
	}
}

function toggleFilterBlock(id) {
	$('#xxlFilterBlock' + id + ' .xxlFilterOptions').toggle();
	
	var src = $('#xxlFilterBlock' + id + ' .xxlBlockToggle').attr('src');
	
	if($('#xxlFilterBlock' + id + ' .xxlFilterOptions').is(':visible')) {
		src = src.replace("open", "close");
	} else {
		src = src.replace("close", "open");
	}
	$('#xxlFilterBlock' + id + ' .xxlBlockToggle').attr('src', src)
}

// listeneinträge filtern
function filterListEntries() {
	$('.xxlListbox').hide();
	$('.xxlListbox')
		.removeClass('xxlListbox')
		.addClass('xxlListboxHidden');
	
	if(ids != null) {
		var len = ids.length;
		for(var i = 0; i < len; i++) {
			$('#xxlListbox' + ids[i])
				.addClass('xxlListbox')
				.removeClass('xxlListboxHidden');
		}
		$('#xxlResultListHolder').hide();
	}
}

// Location in Merkliste speichern
function storeLoc(id) {
	$.ajax({
		url: abs_path + 'ajax.php',
		data: '_load=storeLoc&_area=' + area + '&_id=' + id,
		method: 'GET',
		success: function(data) {
			// link verstecken
			$('#xxlListbox' + id + ' .xxlMerkliste').hide();
			$('#xxlLocationDetail' + id + ' .xxlMerklisteDetail').hide();
			// anzahl aktualisieren
			$('#xxlLocationMerklistWidget .xxlCount').html(data);
		}
	});
}

// "hinzufügen"-link bei locations auf der merkliste ausblenden, merklistenwidget anpassen
// link merklisten-widget an fancybox binden
// wird nur bei pageload aufgerufen, wg. caching in php nicht möglich
function checkCollection() {
	$.ajax({
		url: abs_path + 'ajax.php',
		data: '_load=getCollectionInfo',
		method: 'GET',
		dataType: 'json',
		success: function(data) {
			var len = data.ids.length;
			for(var i = 0; i < len; i++) {
				$('#xxlListbox' + data.ids[i] + ' .xxlMerkliste').hide();
				$('#xxlLocationDetail' + data.ids[i] + ' .xxlMerklisteDetail').hide();
			}
			$('#xxlLocationMerklistWidget .xxlCount').html(len + " Locations");
		}
	});
	
	setMerklistWidget();
}

function setMerklistWidget() {
	$('#xxlShowLocList').fancybox({
		ajax: {
			type: "GET",
			data: '_load=getCollection&_lang=' + lang + '&_area=' + area
		},
		autoScale: false,
		autoDimensions: false,
		width: 500,
		height: '75%',
		onComplete: function(data) {
			$('#fancybox-content').css('background-color', '#ffffff');
			$('#xxlRequestForm').submit(function() {
				var fields = ['xxlComp', 'xxlCont', 'xxlStr', 'xxlPLZ', 'xxlCty', 'xxlTel', 'xxlTitle', 'xxlDate'];
				
				for(var i = 0; i < fields.length; i++) {
					if (xxlCheckEmpty ($("#" + fields[i]), 'Bitte füllen Sie alle Pflichtfelder aus') == false) {
						addError(fields[i]);
						return false;
					}
				}
				if (xxlCheckEmail ($("#xxlMail"), 'Bitte geben Sie eine gültige E-Mail-Adresse ein') == false) {
					addError('xxlMail');
					return false;
				}
				$.ajax({
					url: abs_path + 'ajax.php',
					data: $('#xxlRequestForm').serialize(),
					method: 'GET',
					success: function(data) {
						$('#xxlRequestForm').remove();
						$('.xxlLocLine').remove();
						$('.xxlFancyCollection .xxlMyImage8').html(data);
						$('.xxlMerkliste').show();
						$('#xxlLocationMerklistWidget .xxlCount').html('0 Locations');
						window.setTimeout(function() {
							$.fancybox.close();
						}, 5000);
					}
				});
				return false;
			});
		}
	});
	$('#xxlShowLocListDetail').fancybox({
		ajax: {
			type: "GET",
			data: '_load=getCollectionDetail&_lang=' + lang + '&_area=' + area
		},
		autoScale: false,
		autoDimensions: false,
		width: 500,
		height: '75%',
		onComplete: function(data) {
			$('#fancybox-content').css('background-color', '#ffffff');
			$('#xxlRequestForm').submit(function() {
				var fields = ['xxlComp', 'xxlCont', 'xxlStr', 'xxlPLZ', 'xxlCty', 'xxlTel', 'xxlTitle', 'xxlDate'];
				
				for(var i = 0; i < fields.length; i++) {
					if (xxlCheckEmpty ($("#" + fields[i]), 'Bitte füllen Sie alle Pflichtfelder aus') == false) {
						addError(fields[i]);
						return false;
					}
				}
				if (xxlCheckEmail ($("#xxlMail"), 'Bitte geben Sie eine gültige E-Mail-Adresse ein') == false) {
					addError('xxlMail');
					return false;
				}
				$.ajax({
					url: abs_path + 'ajax.php',
					data: $('#xxlRequestForm').serialize(),
					method: 'GET',
					success: function(data) {
						$('#xxlRequestForm').remove();
						$('.xxlLocLine').remove();
						$('.xxlFancyCollection .xxlMyImage8').html(data);
						$('.xxlMerkliste').show();
						$('#xxlLocationMerklistWidget .xxlCount').html('0 Locations');
						window.setTimeout(function() {
							$.fancybox.close();
						}, 5000);
					}
				});
				return false;
			});
		}
	});
}

/**
 *	error-klasse für nicht ausgefüllte formularfelder hinzufügen. Klasse wird bei Änderung des Felds wieder entfernt
 *	@param id HTML-ID des nicht korrekt ausgefüllten Felds
 */
function addError(id) {
	$('#' + id).addClass("xxlError");
	$('#' + id).focus(function() {
		$('#' + id).removeClass("xxlError");
		$('#' + id).select();
	});
}

function removeLoc(id) {
	$('#xxlLocLine' + id).remove();
	$.ajax({
		url: abs_path + 'ajax.php',
		data: '_load=removeLoc&_id=' + id,
		success: function(data) {
			var count = parseInt(data);
			
			$('#xxlListbox' + id + ' .xxlMerkliste').show();
			if(count==0 || count>1) {
				count = count + " Locations";
			} else {
				count = count + " Location";
			}
			$('#xxlLocationMerklistWidget .xxlCount').html(count);
			if(count == 0) {
				$.fancybox.close();
			}
		}
	});
}

function resetFilter(event) {
	$('input:checked').removeAttr('checked');
	$('option:selected').removeAttr('selected');
	$('.xxlListbox_hidden')
		.removeClass('listbox_hidden')
		.addClass('listbox');
	
	$('.datepicker').val('');
	
	if(typeof event == "undefined" || !event) {
		$('#xxlSearchForm_age').show();
		
		$('#xxlResultListHolder').show();
		loadList($('#navID').val());
	} else {
		filterEventList(true);
	}
}

function locationDetailBlaetter() {
	//SetTimeout weil die Elemente sonst durch die Bildergalerie überschrieben werden
	window.setTimeout(function() {  
		if($('#xxlLocationBlaettern .xxlForward').length > 0) {
			forwarddata = $('#xxlLocationBlaettern .xxlForward a[href]').get(); //mit .get() den Link des nächsten Artikel holen und danach im Header ausgeben
			$("#xxlMultiHeader").append("<div id=\"xxlNext\"><a href=\"" + forwarddata + "\">&nbsp;</a></div>");
		}
		if($('#xxlLocationBlaettern .xxlBack').length > 0) {
			backdata = $('#xxlLocationBlaettern .xxlBack a[href]').get(); //mit .get() den Link des nächsten Artikel holen und danach im Header ausgeben
			if(typeof backdata == "object") {
				var help = '';
				for(var i = 0; i < backdata.length; i++) {
					if(backdata[i].toString().indexOf('loadList') == -1) {
						help = backdata[i].toString();
					}
				}
				backdata = help;
			}
			$("#xxlMultiHeader").append("<div id=\"xxlPrev\"><a href=\"" + backdata + "\">&nbsp;</a></div>");
		}
	},300);
}

$('document').ready(function(){
	if(typeof initHeader == "function") {
		initHeader();
	}
	smallscreen();
	setMapCheckboxes();
	initFancyboxGallery();
	if($('.xxlListbox').length > 0 && !document.getElementById ('xxlLocationList') && !$('.xxlJumplist').html()) {
		initJumplist();
		if($('.xxlFilterBlock').length) {
			$('.xxlFilterBlock').show();
		}
	}
});


