jQuery(function($) {


	// Bildergalerie mit Ligthbox versehen
	if ($('div.gallery').length > 0) {
		$('div.gallery a').lightbox({
			fileLoadingImage : 'http://media.seitenbox.de/img/lightbox/loading.gif',
			fileBottomNavCloseImage : 'http://media.seitenbox.de/img/lightbox/closelabel.gif',
			strings : {
				help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
				prevLinkTitle: 'zurück',
				nextLinkTitle: 'weiter',
				prevLinkText:  '&laquo; Zurück',
				nextLinkText:  'Weiter &raquo;',
				closeTitle: 'Schließen',
				image: 'Bild ',
				of: ' von '
			},
			useImageAltAsTitle: true
		});
		// wenn Option "mit Hover-Effekt" (Lupeneffekt), dann:
		$('div.gallery.hasHoverEffect > a img').each(function(e){
			// URL des Bildes extrahieren, Verzeichnes "small" in "big" ändern und als URL in den Title-Tag schreiben fuer den Lupeneffekt
			src = $(this).attr('src');
			src = src.replace("/small/", "/big/");
			$(this).attr('title', '<img title="" alt="" src="' + src + '"/>');
			// Titel-Tag im Link leeren, damit beim Lupeneffekt kein System-Tooltip erscheint
			$(this).parent().attr("title", "");
		});
		$('div.gallery.hasHoverEffect > a img').easyTooltip({
		    tooltipId: 'hoverThumbnail',
		    yOffset: 50,
		    xOffset: 15
		});
	}

    // einzelnes Bild mit Lightbox
    $('a.lightbox').lightbox({
        fileLoadingImage: 'http://media.seitenbox.de/img/lightbox/loading.gif',
        fileBottomNavCloseImage: 'http://media.seitenbox.de/img/lightbox/closelabel.gif',
        strings: {
            help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
            prevLinkTitle: 'zurück',
            nextLinkTitle: 'weiter',
            prevLinkText: '&laquo; Zurück',
            nextLinkText: 'Weiter &raquo;',
            closeTitle: 'Schließen',
            image: 'Bild ',
            of: ' von '
        },
        useImageAltAsTitle: true
    });
    // einzelnes Bild mit Lupeneffekt
    // wenn Option "mit Hover-Effekt" (Lupeneffekt), dann:
    $('a.hasHoverEffect > img').each(function (e) {
        // URL des Bildes extrahieren, Verzeichnes "small" in "big" ändern und als URL in den Title-Tag schreiben fuer den Lupeneffekt
        src = $(this).attr('src');
        src = src.replace("/small/", "/big/");
        $(this).attr('title', '<img title="" alt="" src="' + src + '"/>');
        // Titel-Tag im Link leeren, damit beim Lupeneffekt kein System-Tooltip erscheint
        $(this).parent().attr("title", "");
    });
    $('a.hasHoverEffect > img').easyTooltip({
        tooltipId: 'hoverThumbnail',
        yOffset: 50,
        xOffset: 15
    });
	
	// Kontaktformular
	if ($('div.contactform').length > 0) {
		$('button.openContactForm').click(function(){
			$('#contactForm').modal({
				opacity: 50,
				closeClass: 'close',
				overlayClose: true
			});
		});
		
		$('button.send').click(function(){
			var data = new Object();
			$('#contactForm table input, #contactForm table textarea').each(function(){
				data[$(this).attr('title')] = $(this).val();
			});
			$.ajax({
				url: '/contactform.php',
				type: 'post',
				data: {
					'data[pid]' : $('input[name="pid"]').val(),
					'data[key]' : $('input[name="key"]').val(),
					'data[values]' : $.toJSON(data)
				},
				success: function(response){
					//Erfolg
					$('<div class="fields" id="contactForm"><h2>Vielen Dank!</h2><p>Ihre Nachrticht wurde gesendet!</p><p><button class="close"> Schließen </button></p></div>').modal({
						opacity: 50,
						closeClass: 'close',
						overlayClose: true
					});
					//alert("Ihre Nachricht wurde verschickt!");
				},
				error: function(){
					alert("Fehler\nBeim Senden der Nachricht ist leider ein Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt noch einmal.");
				}
			});
			$.modal.close();
		});
	}
	
	// Onlineservice (GWH)
	
	if ($('div#onlineservice').length > 0) {
		$('button.send').click(function(){
            var data = new Object();
            var valid = true;
            $('#onlineservice input').removeClass('error');
            $('#onlineservice table input, #onlineservice table textarea').each(function(){
                if ($(this).attr('type') == 'radio') {
                	if($('input[title="'+$(this).attr('title')+'"]:checked').length > 0) {
                		data[$(this).attr('title')] = $('input[title='+$(this).attr('title')+']:checked').val();
                	}
                	else {
                		data[$(this).attr('title')] = 'Keine Angabe';
                	}
                }
                else if ($(this).attr('type') == 'checkbox') {
                	if($('input[title="'+$(this).attr('title')+'"]:checked').length > 0) {
                		data[$(this).attr('title')] = $('input[title='+$(this).attr('title')+']:checked').val();
                	}
                	else {
                		data[$(this).attr('title')] = 'Nein';
                	}
                }
                else {
                	data[$(this).attr('title')] = $(this).val();
                	// validate: highlight if empty
                	if ($(this).hasClass('required') && $(this).val() == "") {
	                	$(this).addClass('error');
                		valid = false;
                	}
                }
            });
            
            if(valid) {
	            $.ajax({
	                    url: '/onlineservice.php',
	                    type: 'post',
	                    data: {
	                            'data[pid]' : $('input[name="pid"]').val(),
	                            'data[type]' : $('input[name="type"]').val(),
	                            'data[key]' : $('input[name="key"]').val(),
	                            'data[values]' : $.toJSON(data)
	                    },
	                    success: function(response){
	                            //Erfolg
	                            $('#text').html("<h3>Vielen Dank</h3><p style='height:250px'>Ihre Nachricht wurde verschickt!</p>");
	                    },
	                    error: function(){
			                    // Fehler
	                            alert("Fehler\nBeim Senden der Nachricht ist leider ein Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt noch einmal.");
	                    }
	            });
            }
            else {
            	alert('Sie haben noch nicht alle erforderlichen Angaben gemacht, bitte prüfen Sie die markierten Eingabefelder.');
            	$('#onlineservice input').focus(function(){
            		$(this).removeClass("error");
            	});
            }
            return false;
        });
	}	
	
	// Online-Formular an Standard-Adresse 
	if ($('div#form').length > 0) {
		$('button.send').click(function(){
            var data = new Object();
            var valid = true;
            $('#form input, #form textarea').removeClass('error');
            $('#form table input, #form table textarea').each(function(){
                if ($(this).attr('type') == 'radio') {
                	if($('input[title="'+$(this).attr('title')+'"]:checked').length > 0) {
                		data[$(this).attr('title')] = $('input[title='+$(this).attr('title')+']:checked').val();
                	}
                	else {
                		data[$(this).attr('title')] = 'Keine Angabe';
                	}
                }
                else if ($(this).attr('type') == 'checkbox') {
                	if($('input[title="'+$(this).attr('title')+'"]:checked').length > 0) {
                		data[$(this).attr('title')] = $('input[title='+$(this).attr('title')+']:checked').val();
                	}
                	else {
                		data[$(this).attr('title')] = 'Nein';
                	}
                }
                else {
                	data[$(this).attr('title')] = $(this).val();
                	// validate: highlight if empty
                	if ($(this).hasClass('required') && $(this).val() == "") {
	                	$(this).addClass('error');
                		valid = false;
                	}
                }
            });
            
            if(valid) {
	            $.ajax({
	                    url: '/contactform.php',
	                    type: 'post',
	                    data: {
	                            'data[pid]' : $('input[name="pid"]').val(),
	                            'data[type]' : $('input[name="type"]').val(),
	                            'data[key]' : $('input[name="key"]').val(),
	                            'data[values]' : $.toJSON(data)
	                    },
	                    success: function(response){
	                            //Erfolg
	                            $('#text').html("<h3>Vielen Dank</h3><p style='height:450px'>Ihre Nachricht wurde verschickt!</p>");
	                    },
	                    error: function(){
			                    // Fehler
	                            alert("Fehler\nBeim Senden der Nachricht ist leider ein Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt noch einmal.");
	                    }
	            });
            }
            else {
            	alert('Sie haben noch nicht alle erforderlichen Angaben gemacht, bitte prüfen Sie die markierten Eingabefelder.');
            	$('#form input').focus(function(){
            		$(this).removeClass("error");
            	});
            }
            return false;
        });
	}
	

	// MP3 mit Flash-Player versehen
	$('a[href$="mp3"]').flash(
		{ src: '/js/singlemp3player.swf', height: 20, width: 150, wmode:"transparent" },
		{ version: 7 },
		function(htmlOptions) {
			$this = $(this);
			htmlOptions.flashvars.file = $this.attr('href');
			$this.before($.fn.flash.transform(htmlOptions));						
		}
	).hide();
	
	
	// Horizontale Flyout-Navi für IE6 : 
	if (checkBrowserName('MSIE 6.0')) {
		$('#navi ul > li').hover(
			// einblenden:
			function(){
				$(this).find('ul').show();
			},
			// ausblenden:
			function(){
				$(this).find('ul').hide();
			}
		);
	}
	
	// Thumbnails fuer Spezial-Galerie ergaenzen
	if ($('div#specialGallery').length > 0) {
		$('#specialGallery img').each(function(e){
			src = $(this).attr('src');
			src = src.replace("/big/", "/small/");
			$(this).attr('rel', src);
		});
	}
	
	// Kalenderdaten laden
	if ($('div.calendar').length > 0) {
		
		$('#text div.calendar').each(function(){
			id = $(this).attr('id');
			$(this).html("");
			$(this).load('/calendar/' + id, null, function (){
				$(this).css({'background' : 'none'});
			});
		});
		

//		id = $('#text div.calendar:first').attr('id');
//		$('#text div.calendar:first').html("");
//		$('#text div.calendar:first').load('/calendar/' + id, null, function (){
//			$('div.calendar:first').css({'background' : 'none'});
//		});
	}
		
});


// Prüfen des User Agents zur Erkennung der Browserversion
function checkBrowserName(name){  
	var agent = navigator.userAgent.toLowerCase();  
	if (agent.indexOf(name.toLowerCase())>-1) {  
		return true;  
	}  
	return false;  
}


function validateMail(address) {
	if (address == "") return false;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(address)) {
		return false;
	}
	return true;
}


// ----------


/*
 * jQuery JSON Plugin
 * version: 2.1 (2009-08-14)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org 
 * website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.
 *
 * It is also influenced heavily by MochiKit's serializeJSON, which is 
 * copyrighted 2005 by Bob Ippolito.
 */

(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);
