var win = window, doc = document;
var isIE = document.all ? true : false;

jQuery(doc).ready(function () {
	/** check cms login */
	if (typeof (cms_login) == 'undefined' || !cms_login) {
		/** cms:not logged in */
		
		/** CSS PREPARATION */
		jQuery('#pageoverlay').css('display', 'block');
		jQuery('#contentContainer').css({'opacity': 0, 'top': 50});
		jQuery('#btnContact').css('display', 'none');
		jQuery('#footerCards').css('top', '200px');
		/** jQuery('#navi').css('width', '+=50px'); required for cufon fontSize */
		
		/** CUFON
		Cufon.replace('#loadingmsg', {fontSize: '24px', fontFamily: 'Lobster'});
		Cufon.replace('#navi>li>a', {fontSize: '21px', fontFamily: 'Lobster', hover: true, textShadow: '1px 1px rgba(0,0,0,0.75)'});
		Cufon.replace('h2', {fontSize: '26px', fontFamily: 'Lobster'});
		Cufon.replace('#contentMain h2.sub', {fontSize: '21px', fontFamily: 'Lobster'});
		Cufon.replace('.footercard h3', {fontSize: '24px', fontFamily: 'Lobster'});
		 */
		/** APPENDINGS */
		/** append:likebutton */
		ajax.load('inc/fblb.php', 'get', '#facebookLikeButton', '', '');
		
		/** append:ajaxnotifier */
		jQuery('body').append('<div id="ajaxnotifier">Seite wird geladen...</div>');
		
		/** CALLS AND INITIALIZATIONS */
		appendRetinaZoom('retinaContainer');
		
		/** SUBNAVIGATION */
		$subs = jQuery('#navi>li').has('ul');
		$subs.each(function (index, element) {
			$obj = jQuery(element);
			$obj.children('display', 'none');
			$obj.mouseover(function() {
				$this = jQuery(this);
				$this.stop(true, true);
				$this.children('ul').fadeIn(240);
			}).mouseleave(function () {
				$this = jQuery(this);
				$this.stop(true, true);
				$this.children('ul').fadeOut(240);
			});
		});
		
		jQuery(win).load(function () {
			/** fade out overlay and view contentContainer and footerCards */
			jQuery('#pageoverlay').fadeOut(1240, function () {
				jQuery('#contentContainer').animate({
					opacity: 1,
					top: 0
				}, 720, function () {
					/** :callback */
					jQuery('#contentContainer').css('filter', 'none'); /** filter fix for IE 6,7,8 */
					jQuery('#btnContact').fadeIn(320);
				});
				jQuery('#footerCards').animate({
					top: 0
				}, 720);
			});
		}); /** end:win.load */
	}
	
}); /** end:doc.ready */




/** LIVE LISTENER */
/** listener:login */
jQuery('a[href="login.php"]').live('click',function () {
	/** prepare logincontainer */
	if(jQuery('#loginContainer').length == 0) 
		jQuery('body').append('<div id="loginContainer"><div id="loginInnerContent" style="display:none;"></div></div>');
	ajax.load('login.php','get',function (data) {
			jQuery('#loginInnerContent').html(data.responseOutput);
			jQuery('#loginContainer').animate({
				top: 0
			},720, function() {
				jQuery('#loginInnerContent').fadeIn(240);
			});
			Cufon.refresh();
	}, '<div id="contentMainInner">', '</div><!--end:contentMainInner-->');
	
	return false;
});

/** listener:bildergalerie */
jQuery('a[href="bildergalerie.php"]').live('click', function () {
	if(jQuery('#galleryContainer').length == 0)
		jQuery('body').append('<div id="galleryContainer"><div id="galleryContainerContent" style="display:none;"></div></div>');
	ajax.load('bildergalerie.php','get',function (data) {
		jQuery('#galleryContainerContent').html(data.responseOutput).css('opacity', '0');
		
		
		jQuery('#galleryContainerContent').waitForImages(function() {
			jQuery('galleryContainer').fadeTo(420, 1);
		},'',true);
		
	}, '<div id="contentMainInner">', '</div><!--end:contentMainInner-->');
	return false;
});

/** listener:ajax */
jQuery('#navi a,.ajax').live('click',function() {
/*	
	@method 3: 	ajax.load(jQuery(this).attr('href'),'get',function(data) {
					alert(data.responseOutput);
				}, '<div id="contentContainer">','</div><!--end:contentContainer-->');
	
	@method 2: ajax.load(jQuery(this).attr('href'),'get','#contentContainer','<div id="contentContainer">','</div><!--end:contentContainer-->');
*/
	if(typeof(cms_login) == 'undefined' || !cms_login) {
		$this = jQuery(this);
		jQuery('#navi li, #contentNavigation li').removeClass('active');
		
		jQuery('#contentMainInner').fadeTo(200, 0, function() {
			var sheight = jQuery('#contentMainInner').height() + 'px';
			ajax.load($this.attr('href'),'get',function(data) {
				jQuery('#contentMain').waitForImages(function() {
					jQuery('#contentMainInner').css('height',sheight);
					
					jQuery('#contentMainInner').html(data.responseOutput).css('height','auto');
					Cufon.refresh();
					var new_height = jQuery('#contentMainInner').height();
					
					jQuery('#contentMainInner').css({'height':sheight}).animate({
						height: new_height
					}, 960).fadeTo(420,1);
					appendRetinaZoom('retinaContainer');
				},'',true);
			},'<div id="contentMainInner">','</div><!--end:contentMainInner-->');
		});
		$this.parent('li').parent('ul').parent('li').addClass('active');
		jQuery('a[href="'+$this.attr('href')+'"]').parent('li').addClass('active');
		$this.parent('li').addClass('active');
		return false;
	};
});


/** LIBRARY */
/** retinazoom.lib */function appendRetinaZoom(className) {
	$objs = jQuery('.'+className);
	$objs.each(function(index, element) {
		$e = jQuery(element);
		$e.append('<div class="retina" style="background:url('+$e.children('img').first().attr('src')+') no-repeat center center #ffffff;"><div>');
		
		$e.mousemove(function(e) {
			$this = jQuery(this);
			$retina = $this.children('.retina').first();
			
			var left, top;
			
			left = (e.pageX-$this.offset().left);
			top = (e.pageY-$this.offset().top);
			
			if($retina.is(':not(:animated):hidden')) {
				$this.trigger('mouseenter');
			};
			
			if(left<0 || top<0 || left > $this.width() || top > $this.height()) {
				if(!$retina.is(':animated')){
					$this.trigger('mouseleave');
				}
				return false;
			};
			
			$retina.css({
				left				: left - $retina.width()/2,
				top					: top - $retina.height()/2,
				backgroundImage		:	$this.children('img').first().attr('src'),
				backgroundPosition	: '-'+(1.6*left)+'px -'+(1.35*top)+'px'
			});
			
		}).mouseenter(function(e){
			$this = jQuery(this);
			$retina = $this.children('.retina').first();
			$retina.stop(true,true).fadeIn(100);
		}).mouseleave(function(e) {
			$this = jQuery(this);
			$retina = $this.children('.retina').first();
			
			$retina.stop(true,true).fadeOut(100);
		});
	});
};

/** ajax.lib */
(function() {
	var xmlhttp;
	var ajax = {
		load: function(uri,method,output,prefix,suffix) {
			if(!(uri && method)) return false;
			xmlhttp = ajax.GetXmlHttpObject();
			if(xmlhttp===null) return false;
			jQuery('#ajaxnotifier').fadeIn(120);
			if(method.toLowerCase() == 'get') {
				/** $_GET */
				var url=uri;
				url=url+"?sid="+Math.random();
				xmlhttp.onreadystatechange=function() {
					ajax.stateChanged(output,prefix,suffix);
				};
				xmlhttp.open("GET",url,true);
				xmlhttp.send(null);
			};
			/*win.location.hash = '/'+uri;*/
		},
		
		stateChanged: function(output,prefix,suffix) {
			if(xmlhttp.readyState == 4) {
				var s,i;
				if(prefix) {
					s = xmlhttp.responseText;
					i = s.indexOf(prefix);
					if(i > -1) {
						s = s.substr(i+prefix.length);
					};
				};
				if(suffix) {
					i = s.indexOf(suffix);
					if(i > -1) {
						s = s.substr(0,i);
					};
				};
				
				xmlhttp.responseOutput = (s)?s:xmlhttp.responseText;
				
				jQuery('#ajaxnotifier').fadeOut(120);
				if(typeof(output) == 'function') {
					return output(xmlhttp);
				};
				if(doc.getElementById(output.substr(1))) {
					if(typeof(jQuery) != "undefined") {
						jQuery('#'+output.substr(1)).fadeTo(240,0, function() {
							jQuery('#'+output.substr(1)).html(xmlhttp.responseOutput);
							if(typeof(Cufon) != 'undefined') Cufon.refresh();
							jQuery('#'+output.substr(1)).fadeTo(240,1);
						});
					} else {
						doc.getElementById(output.substr(1)).innerHTML = xmlhttp.responseOutput;
						if(typeof(Cufon) != 'undefined') Cufon.refresh();
					};
				};
			};
		},
		
		GetXmlHttpObject: function() {
			if(win.XMLHttpRequest) return new XMLHttpRequest();
			if(win.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
			return null;
		}
	};
	win.ajax = ajax;
})();

/** .lib | waitforimages,  */
;(function($) {
    $.fn.waitForImages = function(finishedCallback, eachCallback, waitForAll) {

        // Handle options object.
        if (typeof finishedCallback === 'object') {
            eachCallback = finishedCallback.each;
            waitForAll = finishedCallback.waitForAll;
            finishedCallback = finishedCallback.finished;
        }

        // Handle missing callbacks.
        finishedCallback = finishedCallback || function() {};
        eachCallback = eachCallback || function() {};

        // Convert waitForAll to Boolean
        waitForAll = !! waitForAll;

        // Ensure callbacks are functions.
        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
            throw new TypeError('An invalid callback was supplied.');
        };

        return this.each(function() {
            // Build a list of all imgs, dependent on what images will be considered.
            var obj = $(this),
                allImgs = [];

            if (waitForAll) {
                // CSS properties which may contain an image.
                var hasImgProperties = $.fn.waitForImages.hasImgProperties || [
                    'backgroundImage',
                    'listStyleImage',
                    'borderImage',
                    'borderCornerImage'
                    ];
                   
                var matchUrl = /url\(['"]?(.*?)\1\)/g;

                // Get all elements, as any one of them could have a background image.
                obj.find('*').filter(function() {
                    var element = $(this);

                    // If an `img` element, add it. But keep iterating in case it has a background image too.
                    if (element.is('img')) {
                        allImgs.push({
                            src: element.attr('src'),
                            element: element[0]
                        });
                    }

                    $.each(hasImgProperties, function(i, property) {
                        var propertyValue = element.css(property);
                        // If it doesn't contain this property, skip.
                        if ( ! propertyValue) {
                            return true;
                        }

                        // Get all url() of this element.
                        var match;
                        while (match = matchUrl.exec(propertyValue)) {
                            allImgs.push({
                                src: match[1],
                                element: element[0]
                            });
                        };
                    });
                });
            } else {
                // For images only, the task is simpler.
                obj.find('img').each(function() {
                    allImgs.push({
                        src: this.src,
                        element: this
                    });
                });
            };

            var allImgsLength = allImgs.length,
                allImgsLoaded = 0;

            // If no images found, don't bother.
            if (allImgsLength == 0) {
                finishedCallback.call(obj[0]);
            };

            $.each(allImgs, function(i, img) {

                var image = new Image;

                image.onload = function() {
                    allImgsLoaded++;
                    eachCallback.call(img.element, allImgsLoaded, allImgsLength);
                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };
                };

                image.src = img.src;
            });
        });
    };
})(jQuery);

/** .acc */
if (!doc) var doc = document;
if (!win) var win = window;

function acc(settings) {
    var settings = jQuery.extend({
        active: 'accActive',
        toggle: 'accToggle',
        content: 'accContent',
        accAnchor: 'accAnchor',
        multi: 'multi',
        openFirst: true
    }, settings);
    var active = settings.active;
    var toggle = settings.toggle;
    var content = settings.content;
    var accAnchor = settings.accAnchor;
    var multi = settings.multi;
    var openFirst = settings.openFirst;
    jQuery('.' + content).hide();
    jQuery('.' + toggle + '.' + multi).each(function () {
        if (jQuery.trim(jQuery(this).text()) == '') {
            jQuery(this).remove()
        };
    });
    $urlElem = jQuery(doc.location.hash);
    $active = $urlElem.hasClass(toggle) ? $urlElem : (openFirst ? jQuery('.' + toggle + ':first') : false);
    if ($active) {
        $active.addClass(active).next('.' + content).show(10, function () {
            if ($urlElem.hasClass(toggle)) {
                var top = $active.offset().top;
                jQuery(win).scrollTop(top)
            };
        });
    };
    jQuery('.' + toggle + ', .' + accAnchor).click(function () {
        $this = jQuery(this);
        $toggler = $this.hasClass(toggle) ? $this : jQuery(jQuery(this).attr('href'));
        var hidden = $toggler.next('.' + content).is(':hidden') ? true : false;
        jQuery('.' + content).slideUp(300);
        jQuery('.' + active).removeClass(active);
        if (hidden) {
            if ($toggler.hasClass(multi)) {
                $toggler.addClass(active).nextUntil('.' + toggle).slideDown(300)
            } else {
                $toggler.addClass(active).next('.' + content).slideDown(300)
            };
        };
    });
};

/** formValidation.lib */
function validateForm(n){var e=0;var d="";var j="";var k="";var b="";for(var a=0;a<document.getElementsByTagName("label").length;a++){d=document.getElementsByTagName("label")[a];if(d.htmlFor){j=document.getElementById(d.htmlFor)}k=d.className;b=d.className.replace(/ error/,"");if(d.form==n&&j){if(j.name=="Rueckruf"){if(j.checked==true){document.getElementById("label-telefon").className+=" required rueckruf"}else{var c=document.getElementById("label-telefon").className.replace(/ required rueckruf/,"");document.getElementById("label-telefon").className=c}}if(k.match(/required/)){if(j.tagName=="SELECT"){if(j.childNodes[1].selected){d.className=b;d.className+=" error";e=1}else{d.className=b}}else{if(j.type=="checkbox"){if(j.checked==false){d.className=b;d.className+=" error";e=1}else{d.className=b}}else{if(j.value==""){d.className=b;d.className+=" error";e=1}else{d.className=b}}}}if(k.match(/number/)){var f=isNumber(j);if(!f&&!k.match(/required/)&&j.value!=""){d.className=b;d.className+=" error";e=1}else{d.className=b}if(!f&&k.match(/required/)){d.className=b;d.className+=" error";e=1}else{if(e==0){d.className=b}}}if(k.match(/mail/)){var l=isMailValid(j);if(!l&&j.value!=""){d.className=b;d.className+=" error";e=1}else{d.className=b}if(!l&&k.match(/required/)){d.className=b;d.className+=" error";e=1}else{if(e==0){d.className=b}}}}}var g=document.createElement("p");g.id="fehlermeldung";document.body.appendChild(g);var m=document.getElementById("fehlermeldung");var h='<span id="fehlermeldungBG"></span><span id="fehlermeldungBox"><strong>Beim Abschicken sind Fehler aufgetreten.</strong> <br />Sie haben eventuell nicht alle Pflichtfelder ausgef&uuml;llt. <br />Die falsch ausgef&uuml;llten Punkte sind <strong class="error">rot</strong> gekennzeichnet.<br /><a href="javascript:;" id="errorclose"><strong>[x] schlie&szlig;en</strong></a></span>';m.innerHTML=h;if(e===0){return true}else{jQuery("#fehlermeldungBG").fadeTo("1","0.5");jQuery("body").addClass("overflow");jQuery("#fehlermeldung").fadeIn(500,function(){window.setTimeout(function(){jQuery("#fehlermeldungBox").fadeIn(500)},200)});jQuery("#errorclose").click(function(){jQuery("#fehlermeldungBox").fadeOut(500,function(){window.setTimeout(function(){jQuery("#fehlermeldung").fadeOut(200);jQuery("body").removeClass("overflow");node=document.getElementById("fehlermeldung");node.parentNode.removeChild(node)},200)})});return false}}function isNumber(a){var b=(isNaN(parseInt(a.value))==true)?false:true;return b}function isMailValid(a){var b=(a.value.match(/^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/))?true:false;return b};
