jQuery(document).ready(
function() {
	 //Inhalts Overlay
	 $("div#overlay").slideToggle("slow");
	 $('#switchOverlay').click(function(){
		$("div#overlay").slideToggle("slow");	
		$("#switchOverlay a").toggleClass("active");		
	});
	
	//Kalender Overlay
	$("#calLink, #agbLink").overlay({
	mask: {
		color: '#eee',		
		opacity: 0.5
	},	
	bottom: 120,
	oneInstance: false,
	closeOnClick: false
	});	
	
	
	//Buchungsanfrage Validator	
	$.tools.validator.localize("de", {
		':email'  		: 'Bitte geben Sie eine korrekte E-Mail-Adresse ein.',
		':number'  		: 'Bitte geben Sie hier eine Zahl ein.',
		'[pattern]'		: 'Bitte geben Sie ein korrektes Datum an.',
		'[required]' 	: 'Bitte f&uuml;llen Sie dieses Feld aus.'
	});	
	$.tools.validator.addEffect("wall", function(errors, event) {
		$.each(errors, function(index, error) {
			showToast(error.input.attr("name") + ': ' + error.messages[0], 'error');
			var input = this.input;
			input.css({borderColor: 'red'}).focus(function()  {
				input.css({borderColor: '#444'});
			});			
		});			
	}, function(inputs)  {	});   // the effect does nothing when all inputs are valid	

	$("#anfrage, #persdat").validator({
	   effect: 'wall',
	   lang: 'de',	   
	   errorInputEvent: null   // do not validate inputs when they are edited  
	}).submit(function(e)  { 	   
	   if (!e.isDefaultPrevented()) {showToast('Daten erfolgreich versendet!', 'success');} 	// when data is valid    
	});	
	
	//Textarea default-Wert löschen
	$("#anmerkungen").click(function() {
		if ($(this).val() == "Ihre Nachricht an uns...") { $(this).val(""); }
	});
	
	//Bildergalerie
	$(".scrollable").scrollable();

	$(".items img").click(function() {

		// see if same thumb is being clicked
		if ($(this).hasClass("active")) { return; }

		// calclulate large image's URL based on the thumbnail URL (flickr specific)
		var url = $(this).attr("src").replace("_k", "");
		var title = $(this).attr("title");
		var htmlStr = $(this).attr("rel");
		
		// get handle to element that wraps the image and make it semi-transparent
		var wrap = $("#image_wrap").fadeTo("medium", 0.6);
		var description = $("#description,#galerie_menu").fadeTo("medium", 0.0);
		// the large image from www.flickr.com
		var img = new Image();


		// call this function after it's loaded
		img.onload = function() {

			// make wrappers fully visible
			wrap.fadeTo("fast", 1);
			description.fadeTo("fast", 1);
			// change the image and description
			wrap.find("img").attr("src", url);
			$("#description p").text(htmlStr);
			$("#description h4").text(title);

		};

		// begin loading the image from www.flickr.com
		img.src = url;

		// activate item
		$(".items img").removeClass("active");
		$(this).addClass("active");

	// when page loads simulate a "click" on the first image
	}).filter(":first").click();

	//Kalender JqueryUI Datepicker-----------------------------
	var disabledDays = new Object();
	function getOccupiedDates() {
		$.ajax({
			async: false,
			global: false,
			url: 'lib/getdate.php',			//Format: {"3-3-2011":1,"3-4-2011":1,"3-10-2011":1,"3-11-2011":1}
			success: function (data) {
				disabledDays = $.parseJSON(data); 
			}
		});		
    };
	getOccupiedDates();	
	
	//deutsche Sprache
	$.datepicker.regional['de'] = {clearText: 'l&ouml;schen', clearStatus: 'aktuelles Datum l&ouml;schen',
			closeText: 'schlie&szlig;en', closeStatus: 'ohne &Auml;nderungen schlie&szlig;en',
			prevText: '&#x3c;zur&uuml;ck', prevStatus: 'letzten Monat zeigen',
			nextText: 'Vor&#x3e;', nextStatus: 'n&auml;chsten Monat zeigen',
			currentText: 'heute', currentStatus: '',
			monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni',
			'Juli','August','September','Oktober','November','Dezember'],
			monthNamesShort: ['Jan','Feb','M&auml;r','Apr','Mai','Jun',
			'Jul','Aug','Sep','Okt','Nov','Dez'],
			monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen',
			weekHeader: 'Wo', weekStatus: 'Woche des Monats',
			dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'W&auml;hle D, M d',
			dateFormat: 'dd.mm.yy', firstDay: 1, 
			initStatus: 'W&auml;hle ein Datum', isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['de']);
	//Ende deutsche Sprache 
			
	//Datepicker statischer Jahreskalender
	$(function() {
		$( "#datepicker" ).datepicker({ 
		numberOfMonths:  [2, 4] ,
		changeMonth: true, 
		changeYear: true,
		showButtonPanel: true,
		showOn: "both",
		buttonImage: "images/calendar.png",
		buttonImageOnly: true,
		buttonText: 'Kalender aufrufen',
		minDate: 0,
		beforeShowDay: function(date){					
			var m = date.getMonth()+1, d = date.getDate(), y = date.getFullYear();
			if(m<10){ m = "0" +m};
			if(d<10){ d = "0" +d};
			var date_str = [m,d,y].join('-');			
						
			if (disabledDays[date_str]) {
				return [false, 'belegt', 'Dieses Datum ist belegt'];
			} else {
				return [true, 'frei', 'Dieses Datum ist noch buchbar'];
			}
		}
		});
	});
	
	//Datepicker für Datumsfelder
	var dates = $( "#anreise, #abreise" ).datepicker({ 
		numberOfMonths: 3,
		changeMonth: true, 
		changeYear: true,
		showButtonPanel: true,
		showOn: "both",
		buttonImage: "images/calendar.png",
		buttonImageOnly: true,
		buttonText: 'Kalender aufrufen',
		minDate: 0,
		beforeShowDay: function(date){					
			var m = date.getMonth()+1, d = date.getDate(), y = date.getFullYear();
			if(m<10){ m = "0" +m};
			if(d<10){ d = "0" +d};
			var date_str = [m,d,y].join('-');			
						
			if (disabledDays[date_str]) {
				return [false, 'belegt', 'Dieses Datum ist belegt'];
			} else {
				return [true, 'frei', 'Dieses Datum ist noch buchbar'];
			}				
		},
		onSelect: function( selectedDate ) {
			var option = this.id == "anreise" ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" );
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings );
			dates.not( this ).datepicker( "option", option, date );
		}

	});
	
});
//Toast-Popup Aufruf----------------------   
function showToast(msg, type) {
	$().toastmessage('showToast', {
		text     		: msg,
		sticky  		: false,
		inEffectDuration: 800,
		stayTime		: 5000,
		position 		: 'top-right',
		type     		: type,
		closeText		: '',
		close    		: function () {	console.log("toast is closed ...");		}
	});
}
//Toast-Popup Plug-In----------------------  
(function($)
{
	var settings = {
				inEffect: 			{opacity: 'show'},	// in effect
				inEffectDuration: 	600,				// in effect duration in miliseconds
				stayTime: 			3000,				// time in miliseconds before the item has to disappear
				text: 				'',					// content of the item. Might be a string or a jQuery object. Be aware that any jQuery object which is acting as a message will be deleted when the toast is fading away.
				sticky: 			false,				// should the toast item sticky or not?
				type: 				'notice', 			// notice, warning, error, success
                position:           'top-right',        // top-left, top-center, top-right, middle-left, middle-center, middle-right ... Position of the toast container holding different toast. Position can be set only once at the very first call, changing the position after the first call does nothing
                closeText:          '',                 // text which will be shown as close button, set to '' when you want to introduce an image via css
                close:              null                // callback function when the toastmessage is closed
            };

    var methods = {
        init : function(options)
		{
			if (options) {
                $.extend( settings, options );
            }
		},

        showToast : function(options)
		{
			var localSettings = {};
            $.extend(localSettings, settings, options);

			// declare variables
            var toastWrapAll, toastItemOuter, toastItemInner, toastItemClose, toastItemImage;

			toastWrapAll	= (!$('.toast-container').length) ? $('<div></div>').addClass('toast-container').addClass('toast-position-' + localSettings.position).appendTo('body') : $('.toast-container');
			toastItemOuter	= $('<div></div>').addClass('toast-item-wrapper');
			toastItemInner	= $('<div></div>').hide().addClass('toast-item toast-type-' + localSettings.type).appendTo(toastWrapAll).html($('<p>').append (localSettings.text)).animate(localSettings.inEffect, localSettings.inEffectDuration).wrap(toastItemOuter);
			toastItemClose	= $('<div></div>').addClass('toast-item-close').prependTo(toastItemInner).html(localSettings.closeText).click(function() { $().toastmessage('removeToast',toastItemInner, localSettings) });
			toastItemImage  = $('<div></div>').addClass('toast-item-image').addClass('toast-item-image-' + localSettings.type).prependTo(toastItemInner);

            if(navigator.userAgent.match(/MSIE 6/i))
			{
		    	toastWrapAll.css({top: document.documentElement.scrollTop});
		    }

			if(!localSettings.sticky)
			{
				setTimeout(function()
				{
					$().toastmessage('removeToast', toastItemInner, localSettings);
				},
				localSettings.stayTime);
			}
            return toastItemInner;
		},

        showNoticeToast : function (message)
        {
            var options = {text : message, type : 'notice'};
            return $().toastmessage('showToast', options);
        },

        showSuccessToast : function (message)
        {
            var options = {text : message, type : 'success'};
            return $().toastmessage('showToast', options);
        },

        showErrorToast : function (message)
        {
            var options = {text : message, type : 'error'};
            return $().toastmessage('showToast', options);
        },

        showWarningToast : function (message)
        {
            var options = {text : message, type : 'warning'};
            return $().toastmessage('showToast', options);
        },

		removeToast: function(obj, options)
		{
			obj.animate({opacity: '0'}, 600, function()
			{
				obj.parent().animate({height: '0px'}, 300, function()
				{
					obj.parent().remove();
				});
			});
            // callback
            if (options && options.close !== null)
            {
                options.close();
            }
		}
	};

    $.fn.toastmessage = function( method ) {

        // Method calling logic
        if ( methods[method] ) {
          return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
          $.error( 'Method ' +  method + ' does not exist on jQuery.toastmessage' );
        }
    };

})(jQuery);
