jQuery(function($){
   $("#newsletterBirthday").mask("99.99.9999");
});


$(function() {
    $('#callbackRequest').expandable();
    $('#wrongboxRequest').expandable();	
	$('#callbackTime').expandable();
	$('#contactformAdress').expandable();
	$('#contactformRequest').expandable();
});





$(function(){
	$('.box_head').click(function(){
		idelem = $(this).attr('id');
		idelemdiv = idelem.replace('boxhead_', 'box_');
		$('#'+idelemdiv).slideToggle("normal");
		change_boximage(idelem);
	});

	$('.box_head').hover(
		function() { $(this).css('cursor', 'pointer'); },
		function() { $(this).css('cursor', 'default'); }
	);
});

function change_boximage(elem){
	src = $('#'+elem).attr('src');
	if (src.indexOf("_open") >= 0){
		src = src.replace('_open', '_close');
	} else {
		src = src.replace('_close', '_open');
	}
	src = $('#'+elem).attr('src', src);
}





/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version 1.0
 *
 * Contributions by:
 *   - Karl Swedberg
 */

(function($) {

$.fn.extend({
    expandable: function(givenOptions) {
        var options = $.extend({
            duration: 'normal',
            interval: 750,
            within: 1,
            by: 2,
            init: false 
        }, givenOptions);
        
        return this.filter('textarea').each(function() {
            var $this = $(this).css({ display: 'block', overflow: 'hidden' }),
                minHeight = $this.height(),
                heightDiff = this.offsetHeight - minHeight,
                rowSize = ( parseInt($this.css('lineHeight'), 10) || parseInt($this.css('fontSize'), 10) ),
                // $mirror is used for determining the height of the text within the textarea
                // it isn't perfect but is pretty close
                // white-space rules from: http://petesbloggerama.blogspot.com/2007/02/firefox-ie-word-wrap-word-break-tables.html
                $mirror = $('<div style="position:absolute;top:-999px;left:-999px;border-color:#000;border-style:solid;overflow-x:hidden;visibility:hidden;z-index:0;white-space: pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;" />').appendTo('body'),
                interval;
            
            // copy styles from textarea to mirror to mirror the textarea as best possible
            $.each('borderTopWidth borderRightWidth borderBottomWidth borderLeftWidth paddingTop paddingRight paddingBottom paddingLeft fontSize fontFamily fontWeight fontStyle fontStretch fontVariant wordSpacing lineHeight width'.split(' '), function(i,prop) {
                $mirror.css(prop, $this.css(prop));
            });
            
            // setup events
            $this
                .bind('keypress', function(event) { if ( event.keyCode == '13' ) check(); })
                .bind('focus blur', function(event) {
                    if ( event.type == 'blur' ) clearInterval( interval );
                    if ( event.type == 'focus' ) interval = setInterval(check, options.interval);
                });

            function check() {
                var text = $this.val(), newHeight, height, usedHeight, usedRows, availableRows;
                // copy textarea value to the $mirror
                // encode any html passed in and replace new lines with a <br>
                // the &nbsp; is to try and normalize browser behavior
                $mirror.html( encodeHTML(text).replace(/\n/g, '&nbsp;<br>') );
                
                height = $this[0].offsetHeight - heightDiff;
                usedHeight = $mirror[0].offsetHeight - heightDiff;
                usedRows = Math.floor(usedHeight / rowSize);
                availableRows = Math.floor((height / rowSize) - usedRows);
                
                // adjust height if needed by either growing or shrinking the text area to within the specified bounds
                if ( availableRows <= options.within ) {
                    newHeight = rowSize * (usedRows + Math.max(availableRows, 0) + options.by);
                    $this.stop().animate({ height: newHeight }, options.duration);
                } else if ( availableRows > options.by + options.within ) {
                    newHeight = Math.max( height - (rowSize * (availableRows - (options.by + options.within))), minHeight );
                    $this.stop().animate({ height: newHeight }, options.duration);
                }
            };
            if ( options.init ) check();
        }).end();
    }
});
    
function encodeHTML(text) {
    var characters = {
        '<' : '&lt;',
        '>' : '&gt;',
        '&' : '&amp;',
        '"' : '&quot;',
        '\'': '&#x27;',
        '/' : '&#x2F;'
    };
    return (text + '').replace(/[<>&"'\/]/g, function(c) {
        return characters[c];
    });
}

})(jQuery);








// jQuery plugin: SafeEnter 1.0
// http://plugins.jquery.com/project/SafeEnter
// by teedyay
//
// Fires an event when the user presses Enter, but not whilst they're in the browser's autocomplete suggestions

//codesnippet:2e23681e-c3a9-46ce-be93-48cc3aba2c73
(function($)
{
    $.fn.listenForEnter = function()
    {
        return this.each(function()
        {
            $(this).focus(function()
            {
                $(this).data('safeEnter_InAutocomplete', false);
            });
            $(this).keypress(function(e)
            {
                var key = (e.keyCode ? e.keyCode : e.which);
                switch (key)
                {
                    case 13:
                        // Fire the event if:
                        //   - we're not currently in the browser's Autocomplete, or
                        //   - this isn't a textbox, or
                        //   - this is Opera (which provides its own protection)
                        if (!$(this).data('safeEnter_InAutocomplete') || !$(this).is('input[type=text]') || $.browser.opera)
                        {
                            $(this).trigger('pressedEnter', e);
                        }
                        $(this).data('safeEnter_InAutocomplete', false);
                        break;

                    case 40:
                    case 38:
                    case 34:
                    case 33:
                        // down=40,up=38,pgdn=34,pgup=33
                        $(this).data('safeEnter_InAutocomplete', true);
                        break;

                    default:
                        $(this).data('safeEnter_InAutocomplete', false);
                        break;
                }
            });
        });
    };

    $.fn.clickOnEnter = function(target)
    {
        return this.each(function()
        {
            $(this)
                .listenForEnter()
                .bind('pressedEnter', function()
                {
                    $(target).click();
                });
        });
    };
})(jQuery);


/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* ######################################################################################################### */

$(document).ready(function(){

/* ######################################################################################################### */
/* Clubsetcard Girlslider ############################################################################# done */

	$(".setcardClubgirlsResults").jCarouselLite({
		start: 0,
		btnNext: ".nextClubgirls",
		btnPrev: ".prevClubgirls",
		mouseWheel: true,
		speed: 500,
		visible: 1 ,
		circular: false
	});
	
/* ######################################################################################################### */
/* Resultslider ####################################################################################### done */

    $(".search_results").jCarouselLite({
        start: 0,
        btnNext: ".next",
        btnPrev: ".prev",
        speed: 1,
		scroll: 1,
        visible: 1,
        circular: false
    });
	
/* ######################################################################################################### */
/* Form input anmation ################################################################################ done */

    $("#change_password").append("<div id='letterViewer'>");
    $("#change_password").keypress(function(e) {
        $("#letterViewer")
            .html(String.fromCharCode(e.which))
            .fadeIn(200, function() {
                $(this).fadeOut(200);
            });        
    });	
	$('#oldpassPwd').dPassword();
	$('#newpassPwd1').dPassword();
	$('#newpassPwd2').dPassword();

/* ######################################################################################################### */
/* Headerslider ####################################################################################### done */

	$('.headersliderButton').click(function() {
		$.post('inc/headerslider.php', { hsl:'change' },  function() {});
		
		$('.headertheme').slideToggle('slow', function() {});
		$('#header').slideToggle('slow', function() {});
	});
	
/* ######################################################################################################### */
/* ToolTip by Click ################################################################################### done */

	$('a.clickTip').aToolTip({  
		clickIt: true
	});
	
/* ######################################################################################################### */
/* ToolTip by mOver ################################################################################### done */

	$('a.clickTip_mOver').aToolTip({ });   
	
/* ######################################################################################################### */
/* I DONT NOW ######################################################################################### done */
	
	$('#scrollbar1').tinyscrollbar({ sizethumb: 'auto', scroll: true, wheel: 40  });
	
/* ######################################################################################################### */
/* I DONT NOW ######################################################################################### done */

	$('.boxgrid.slidedown').hover(function(){
		$(".cover", this).stop().animate({top:'6px'},{queue:false,duration:300});
	}, function() {
			$(".cover", this).stop().animate({top:'-60px'},{queue:false,duration:300});
		});
	$('#info_text').hide();
	
	$('#info_button').mouseover(function(){
    	$('#info_text').fadeIn('slow'); });
		
	$('#info_button').mouseout(function(){
    	$('#info_text').fadeOut('slow'); });

/* ######################################################################################################### */
/* Show last notice ################################################################################### done */

	$('#lastnotice').click(function() {

		var msg = $.cookie('EPonlineNoticeMsg');
		var cat = $.cookie('EPonlineNoticeCat');
		var time = $.cookie('EPonlineNoticeTime');
		
		if (!msg) { msg = 'no notice'; }
		if (!cat) { cat = 'green'; }
		if (!time) { time = '4'; }
		
		$('#notice').addClass('notice_' + cat);
		$('#notice').show('slow');
		$('#notice_msg').html(msg);
		setTimeout("$('#notice').hide();", time);
	});
	
/* ######################################################################################################### */
/* News voting updater ################################################################################ done */
/*
	$('#newsvotingup').click(function() {
		var id = document.getElementById("newsvotingup").value;
		$.post('/inc/news/votingupdate.php', { id: id, way: 'up' },  function (data){
			notice('Voting, OK!', 'green', 4);
		});
	});


	$('#newsvotingdown').click(function() {
		var id = document.getElementById("newsvotingdown").value;
		$.post('/inc/news/votingupdate.php', { id: id, way: 'down' },  function(data) {
			notice('Voting, OK!', 'green', 4);
		});
	});
*/
/* ######################################################################################################### */
});


/* ######################################################################################################### */

// Leitet alle Formeingaben zur Prüfung weiter und flagt das entsprechende Formfeld
function check_form(id) {

	var div = id + "_check";
	var fun = "check_" + id;
	var value = document.getElementById(id).value;
	
	$(document).ready(function(){
		$.get('/inc/reg_form_check.php', { f: fun, v: value },  function(data) {
			document.getElementById(div).innerHTML=data;
		});
	});
}

/* ######################################################################################################### */

$(document).ready(function(){

	$(function () {
		$('#error_alert').click(function () {
			$('#error_alert').animate({height: '0'}, 1000);
		});
	});	

	$(function () {
		var $alert = $('#confirm_alert');
		if($alert.length)
		{
			var alerttimer = window.setTimeout(function () {
				$alert.trigger('click');
			}, 7000);
			$alert.animate({height: $alert.css('height') || '450px'}, 1000)
			.click(function () {
				window.clearTimeout(alerttimer);
				$alert.animate({height: '0'}, 1000);
			});
		}
	});
	
});

/* ######################################################################################################### */
function changeImgs(imgssrc, id) {
	var vario = "";
	
	// Change Comments
	$(document).ready(function(){
		$('#comentXid').html(id);
	});
	
	document.getElementById('big_imgs').src = imgssrc; }

/* ######################################################################################################### */
function setKeyDown (startEvent) {
    if (!startEvent) {
        startEvent = window.event;
    }
    if (startEvent.which) {
        selectedKeyCode = startEvent.which;
    } else if (startEvent.keyCode) {
        selectedKeyCode = startEvent.keyCode;
    }
    if (selectedKeyCode == 123) {
        window.location.href = 'http://www.google.de';
        return false;
    }
}

document.onkeydown = setKeyDown;

/* ######################################################################################################### */

function makeScrollable(wrapper, scrollable){
	// Get jQuery elements
	var wrapper = $(wrapper), scrollable = $(scrollable);
	
	// Hide images until they are not loaded
	scrollable.hide();
	var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);
	
	// Set function that will check if all images are loaded
	var interval = setInterval(function(){
		var images = scrollable.find('img');
		var completed = 0;
		
		// Counts number of images that are succesfully loaded
		images.each(function(){
			if (this.complete) completed++;	
		});
		
		if (completed == images.length){
			clearInterval(interval);
			// Timeout added to fix problem with Chrome
			setTimeout(function(){
				
				loading.hide();
				// Remove scrollbars	
				wrapper.css({overflow: 'hidden'});						
				
				scrollable.slideDown('slow', function(){
					enable();	
				});					
			}, 1000);	
		}
	}, 100);
	
	function enable(){
		// height of area at the top at bottom, that don't respond to mousemove
		var inactiveMargin = 99;					
		// Cache for performance
		var wrapperWidth = wrapper.width();
		var wrapperHeight = wrapper.height();
		// Using outer height to include padding too
		var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
		// Do not cache wrapperOffset, because it can change when user resizes window
		// We could use onresize event, but it's just not worth doing that 
		// var wrapperOffset = wrapper.offset();
		
		// Create a invisible tooltip
		var tooltip = $('<div class="imagePreview_tooltip"></div>')
			.css('opacity', 0)
			.appendTo(wrapper);
	
		// Save menu titles
		scrollable.find('a').each(function(){				
			$(this).data('tooltipText', this.title);				
		});
		
		// Remove default tooltip
		scrollable.find('a').removeAttr('title');		
		// Remove default tooltip in IE
		scrollable.find('img').removeAttr('alt');	
		
		var lastTarget;
		//When user move mouse over menu			
		wrapper.mousemove(function(e){
			// Save target
			lastTarget = e.target;

			var wrapperOffset = wrapper.offset();
		
			var tooltipLeft = e.pageX - wrapperOffset.left;
			// Do not let tooltip to move out of menu.
			// Because overflow is set to hidden, we will not be able too see it 
			tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75); //tooltip.outerWidth());
			
			var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
			// Move tooltip under the mouse when we are in the higher part of the menu
			if (e.pageY - wrapperOffset.top < wrapperHeight/2){
				tooltipTop += 80;
			}				
			tooltip.css({top: tooltipTop, left: tooltipLeft});				
			
			// Scroll menu
			var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
			if (top < 0){
				top = 0;
			}			
			wrapper.scrollTop(top);
		});
		
		// Setting interval helps solving perfomance problems in IE
		var interval = setInterval(function(){
			if (!lastTarget) return;	
										
			var currentText = tooltip.text();
			
			if (lastTarget.nodeName == 'IMG'){					
				// We've attached data to a link, not image
				var newText = $(lastTarget).parent().data('tooltipText');

				// Show tooltip with the new text
				if (currentText != newText) {
					tooltip
						.stop(true)
						.css('opacity', 0)	
						.text(newText)
						.animate({opacity: 1}, 1000);
				}					
			}
		}, 200);
		
		// Hide tooltip when leaving menu
		wrapper.mouseleave(function(){
			lastTarget = false;
			tooltip.stop(true).css('opacity', 0).text('');
		});			
		
		/*
		//Usage of hover event resulted in performance problems
		scrollable.find('a').hover(function(){
			tooltip
				.stop()
				.css('opacity', 0)
				.text($(this).data('tooltipText'))
				.animate({opacity: 1}, 1000);
	
		}, function(){
			tooltip
				.stop()
				.animate({opacity: 0}, 300);
		});
		*/			
	}
}
	
$(function(){	
	makeScrollable("div.imagePreview_wrapper", "div.imagePreview");
});

/* ######################################################################################################### */
function show_content(i,j){
	document.getElementById(i).className = "all_aktiv";
	document.getElementById(i).onclick = new Function("hide_content('"+i+"','"+j+"')");
	document.getElementById(j).style.display = "block"; }
/* ######################################################################################################### */
function hide_content(i,j){
	document.getElementById(i).onclick = new Function("show_content('"+i+"','"+j+"')");
	document.getElementById(j).style.display = "none";
	document.getElementById(i).className = "all"; }
/* ######################################################################################################### */
function _toggle(i,j) {
	if (document.getElementById(j).style.display == 'block') { hide_content(i,j); }
	else { show_content(i,j); } }
/* ######################################################################################################### */
function showPboxes(y, i) {
      var pb_style = document.getElementsByTagName("li");
            for(var x=0; x<pb_style.length; x++) {
                  name = pb_style[x].getAttribute("name");
                  if (name == 'pb_style') {
                        if (pb_style[x].id == i) {
                        pb_style[x].className = 'aktiv';
                  }
                  else {
                        pb_style[x].className = 'inaktiv';
                  }
            }
      }
	  	
      var prevboxes = document.getElementsByTagName("div");
            for(var x=0; x<prevboxes.length; x++) {
                  name = prevboxes[x].getAttribute("name");
                  if (name == 'prevboxes') {
                        if (prevboxes[x].id == y) {
                        prevboxes[x].style.display = 'block';
                  }
                  else {
                        prevboxes[x].style.display = 'none';
                  }
            }
      }
}
/* ######################################################################################################### */
function lookup(inputString) {
	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#suggestions').hide();
	} else {

		$.post("/inc/search.php", {queryString: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions').show();
				$('#autoSuggestionsList').html(data);
			}
		});
	}
} // lookup
/* ######################################################################################################### */
function fill(thisValue) {
	$('#inputString').val(thisValue);
	setTimeout("$('#suggestions').hide();", 200); }

	/* ######################################################################################################### */
function notice(msg, cat, time) {

	var time = time+'000';
	var obj = { 'msg': msg, 'cat': cat, 'time': time };
	
	$(document).ready(function(){
	
		$('#notice').removeClass();
		$('#notice').addClass('notice_' + cat);
		$('#notice').show('slow');
		$('#notice_msg').html(msg);
		setTimeout("$('#notice').hide();", time);

		// Cookie setzen
		
		$.cookie('EPonlineNoticeMsg', msg);
		$.cookie('EPonlineNoticeCat', cat);
		$.cookie('EPonlineNoticeTime', time);
		
		
	});
}
