// StartUpJobs
//-----------------------------------------//
$(document).ready(function() {
	var marktID		= false;
	var mtTimeTable	= false;	
	
	// MarktID aus Cookie lesen und als globale Variable speichern
	getMarktID();
	
	// iframe mit Marktinfo im Header generieren
	createMarktInfo();
	
	// hinterlegte Öffnungszeiten, falls vorhanden, includieren
	getOpeningTimes();
	//setOpeningTimesInformation02();
	
	// M507 - Kommunikationsfeld
	ppmFX_M507();
	
	// M508 - Slideshow
	$('div.M508-slideshow').ppmFX_508_slideshow();
	
	// M508 - Thumbnails
	$('div.M508-thumbnails').ppmFX_508_thumbnails();
	
	// M509 - Formulare
	ppmFX_509();
	
	// M517 - Nachrichtenanreißer
	ppmFX_M517();
});
//-----------------------------------------//


// MarktID aus Cookie lesen
function getMarktID() {
	marktID = getmktcookie();
	marktID	= parseInt(marktID);
}

function setOpeningTimesInformation02() {
	//if (typeof marktID == 'number' && isNaN(marktID) === false && marktID == 1000000020) {	// TESTING
		var infoText = '&Ouml;ffnungszeiten: Hinweise am Markt beachten.';
		$('span#openingTimes01').html(infoText);
		$('#marktsuche_iframe span#openingTimes02').html(infoText);
	//}																						// TESTING
}

// prüfen ob MarktID vorhanden und Öffnungszeiten reinholen
function getOpeningTimes() {
	if (typeof marktID == 'number' && isNaN(marktID) === false) 
	{		
		// Öffnungszeiten reinholen
		$.getScript("/mein-markt/"+marktID+"/info/mtOeffnungszeiten.js", function()
		{
			if (isNoNaturalPhraseForOpeningTimesAvailable('span#openingTimes01')) {
				// aktuelle Öffnungszeiten für den Tag als Satz
				var naturalPhrase = createNaturalPhraseForActualOpeningTimes();
				$('span#openingTimes01').html(naturalPhrase);
			}
			
			// Script wird direkt im iframe aufgerufen 
			if (isNoNaturalPhraseForOpeningTimesAvailable('#marktsuche_iframe span#openingTimes02')) {
				// aktuelle Öffnungszeiten für den Tag als Satz
				var naturalPhrase = createNaturalPhraseForActualOpeningTimes();
				$('#marktsuche_iframe span#openingTimes02').html(naturalPhrase);
			}
			
			// aktuelle Öffnungszeiten für den Tag als Satz
			$('iframe').ready(function() {
				var elem = $('iframe').contents().find('span#openingTimes02:empty').size();
				// wenn elem = 1, dann wurde ein leeres Element gefunden
				if (typeof elem === 'number' && elem === 1) {
					var naturalPhrase = createNaturalPhraseForActualOpeningTimes();
					$('iframe').contents().find('span#openingTimes02').html(naturalPhrase);
				}
					
			});
					
		});	
	}
}

// M507 - Kommunikationsfeld
function ppmFX_M507() {
	$('div.M507').each(function() {
		$(this).find('div.itemBox-button a').each(function(intIndex) {
			$(this).hover(function() {
				$(this).parent().parent().parent().find('div.cell-00 a img').hide();
				$(this).parent().parent().parent().find('div.cell-00 a img:eq('+intIndex+')').css('display', 'block');
			});
		});
	});
}

// M517 - Nachrichtenanreißer
function ppmFX_M517() {
	$('div.M517').each(function(intIndex, jObj) {
		if ($('a img', jObj).length === 0 || $('a img', jObj).attr('src') == '') {
			$('a img', jObj).remove();
			$('div.cell-01', jObj).css('width', 'auto');
		}
	});
}

// THUMNAILS
(function($) {
	$.fn.ppmFX_508_thumbnails = function(options) {
		
		$.fn.ppmFX_508_thumbnails.defaults = {
			maxImgPerPage: 12
		};
		
		var opts = $.extend({}, $.fn.ppmFX_508_thumbnails.defaults, options);
		var jsLoadSate = false;
		
		function getGalleryCSS() {
			// get CSS for gallery
			$.get('/script/toolbox/highslide/theme/highslide.css', function(cssData) {
				$('head').append('<style type="text/css">'+cssData+'</style>');
			});
			
			if (ie6Check() === true) {
				// get IE6-CSS for gallery
				$.get('/script/toolbox/highslide/theme/highslide-ie6.css', function(cssData) {
					$('head').append('<style type="text/css">'+cssData+'</style>');
				});
			}
		}
		function ie6Check() {
			if (jQuery.browser.msie && parseInt(jQuery.browser.version) === 6) {
				return true;	
			}
			return false;
		}
		
		return this.each(function(intIndex, jObj) {
			
			setNumberOfImages = function(jObj) {						
				$(jObj).data('dataStorage').numberOfImages = $('div.itemBox-image', jObj).size();						
			}
			setNumberOfPages = function(numberOfImages) {
				$(jObj).data('dataStorage').numberOfPages = Math.ceil($(jObj).data('dataStorage').numberOfImages/opts.maxImgPerPage);
			}
			setPageNumbers = function(jObj) {
				$('span.galleryActualPage', jObj).text($(jObj).data('dataStorage').actualPage);
				$('span.galleryNumberOfPages', jObj).text($(jObj).data('dataStorage').numberOfPages);
			}
			setPageClassesAndSlideGroups = function(jObj) {
				var imgPageCounter = 1;
				
				$('div.itemBox-image', jObj).each(function(imgCounter, jObj2) {				
					imgCounter++;
					if (imgCounter <= (opts.maxImgPerPage*imgPageCounter)) {
						$(this).addClass('galleryPageNumber_'+imgPageCounter);
						$(this).find('a').each(function() {
							$(this).attr('rel', 'galleryGroup-'+$(jObj).data('dataStorage').modulCounter+imgPageCounter);
							this.onclick = function() {
								return hs.expand(this, { slideshowGroup: $(this).attr('rel') });
							};
						});
					} else {
						imgPageCounter++;
						$(this).addClass('galleryPageNumber_'+imgPageCounter);
						$(this).find('a').each(function() {
							$(this).attr('rel', 'galleryGroup-'+$(jObj).data('dataStorage').modulCounter+imgPageCounter);
							this.onclick = function() {
								return hs.expand(this, { slideshowGroup: $(this).attr('rel') });
							};
						});
					}
				});	
			}
			imageShow = function(jObj, event) {
				if (event == 'onload') {
					$('div.itemBox-image', jObj).hide();
					$('div.itemBox-image.galleryPageNumber_'+$(jObj).data('dataStorage').actualPage, jObj).show();
				} else {
					$('div.itemBox-image:visible', jObj).fadeOut('def', function () {
						$('div.itemBox-image.galleryPageNumber_'+$(jObj).data('dataStorage').actualPage, jObj).fadeIn('def');
					});
				}
				setPageNumbers(jObj);
			}
			goNext = function(jObj) {
				$(jObj).data('dataStorage').actualPage++;
				if ($(jObj).data('dataStorage').actualPage > $(jObj).data('dataStorage').numberOfPages) {
					$(jObj).data('dataStorage').actualPage = $(jObj).data('dataStorage').numberOfPages;
				} else {
					imageShow(jObj);
				}
				return hs.close();
			}
			goPrev = function(jObj) {
				$(jObj).data('dataStorage').actualPage--;					
				if ($(jObj).data('dataStorage').actualPage < 1) {
					$(jObj).data('dataStorage').actualPage = 1;
				} else {
					imageShow(jObj);
				}
				return hs.close();
			}					

				
			$(jObj).data('dataStorage', { actualPage: 1, numberOfImages: null, numberOfPages: null, modulCounter: intIndex});
			
			setNumberOfImages(jObj);
			setNumberOfPages();
									
			// get sources
			if (jsLoadSate === false) {
				getGalleryCSS();
				jsLoadSate = true;						
			}
			
			$.getScript('/script/toolbox/highslide/highslide.js', function() {
				// set additional image wrapper
				hs.Expander.prototype.onAfterExpand = function() {
					$('img.highslide-image').wrap('<div class="highslide-image-wrapper-x"></div>').css('border', '1px solid #dfdfdf');
					$('div.highslide-image-wrapper-x').prepend('<div class="galleryHoverNav">'+
																	'<a href="#" class="prevLink" onclick="return hs.previous(this);"></a>'+
																	'<a href="#" class="nextLink" onclick="return hs.next(this);"></a>'+
																'</div>'+
																'<div class="btn btn-galleryClose" onclick="return hs.close(this);">'+
																	'<b>schließen</b>'+
																'</div>');
					var elemWidth	= $('img.highslide-image').width();
					var elemHeight	= $('img.highslide-image').height();					
					$('div.galleryHoverNav').width(elemWidth).height(elemHeight);
					
					var imageNumbers = $('.highslide-number').text();
					$('.highslide-container .itemBox-navBar .itemBox-text').text(imageNumbers);
				}
											
				// set special gallery settings
				hs.align 					= 'center';
				hs.preserveContent			= true;
				hs.showCredits				= false;
				hs.allowMultipleInstances	= false;
				hs.graphicsDir				= 'http://www.rewe.de/script/toolbox/highslide/theme/images/';
				hs.expandCursor				= null;
				hs.restoreCursor			= null;
				hs.allowWidthReduction		= true;
				hs.wrapperClassName 		= 'wide-border';
				hs.captionId				= 'the-caption';
				hs.numberPosition 			= 'caption';
				hs.lang.number 				= 'Bild %1 von %2';
				hs.addSlideshow({
					// slideshowGroup: 'group1',
					repeat: false,
					useControls: true,
					fixedControls: true,
					overlayOptions: {
						opacity: 0.0,
						//position: 'top center',
						hideOnMouseOut: true
					}
				});
				hs.Expander.prototype.onAfterGetCaption = function () {					
					this.caption.innerHTML = this.caption.innerHTML.replace("{imgAltTag}", this.thumb.alt);
				}	
			});
			
			// show gallery-navBar
			$('div.itemBox-navBar:hidden', jObj).show();
			// Inhaltshöhe festlegen
			$('div.cell-01', jObj).css('height', '345px');
			
			// create caption markup
			/*$('div.cell-00', jObj).append('<div class="highslide-caption" id="the-caption" style="display: none;">'+
												'<div class="itemBox-navBar">'+
													'<div class="itemBox-navBar-Inner">'+
														'<a href="#" class="btn btn-galleryPrevious" onclick="return hs.previous(this);"><b>zurück</b></a>'+
														'<div class="itemBox-text typeFace-text">'+
															'Bild&nbsp;<span class="galleryActualPage"></span>&nbsp;von&nbsp;<span class="galleryNumberOfPages"></span>'+
														'</div>'+
														'<a href="#" class="btn btn-galleryNext" onclick="return hs.next(this);"><b>vor</b></a>'+
														'<div class="clearing"></div>'+
													'</div>'+
												'</div>'+
												'<div class="itemBox-caption typeFace-caption">{imgAltTag}</div>'+
											'</div>');*/
			setPageClassesAndSlideGroups(jObj);
			imageShow(jObj, 'onload');
			
			// goto previous gallery page
			$('a.btn-galleryPrevious', jObj).click(function(){
				goPrev(jObj);
				return false;
			});
			// goto next gallery page
			$('a.btn-galleryNext', jObj).click(function(){
				goNext(jObj);
				return false;
			});
		});
	}
})(jQuery);


// SLIDESHOW
(function($) {
	$.fn.ppmFX_508_slideshow = function(options) {
		
		$.fn.ppmFX_508_slideshow.defaults = {
			slideShowDelay: 4000
		};
		
		var opts = $.extend({}, $.fn.ppmFX_508_slideshow.defaults, options);
		var jsLoadSate = false;
		
		return this.each(function(intIndex, jObj) {
			
			$.getScript('/script/toolbox/jquery_jcarousel/jquery.jcarousel.pack.js', function() {
				$('div.itemBox-imageShow ul', jObj).jcarousel({
			        scroll: 4,
			        initCallback: mycarousel_initCallback,
			        buttonNextHTML: null,
			        buttonPrevHTML: null
			    });
			});
				
			// show gallery-navBar
			$('div.itemBox-navBar:hidden', jObj).show();
			// show slideshow
			$(this).show();
			
			function mycarousel_initCallback(carousel) {
				
				playTheSlideShow = function(jObj, carousel) {
					var nextElem = $('div.itemBox-imageShow li.active', jObj).next(':visible');
					var imgCount = $(nextElem).attr('jcarouselindex');
					imgCount = parseInt(imgCount);
					
					if (isNaN(imgCount) === false) {
						if ((carousel.last - imgCount) < 2) {
							carousel.scroll(jQuery.jcarousel.intval(imgCount-2));
						}
						setTimer(jObj, carousel);
					} else {
						$('a.btn-galleryPause', jObj).removeClass('btn-galleryPause').addClass('btn-galleryPlay');
						stopTimer(jObj);
					}
					
					$('a', nextElem).click();
				}
				setTimer = function(jObj,carousel) {
					var setTimeoutFunc = function () { playTheSlideShow(jObj, carousel);};
					jObj.slideShowTimer = setTimeout(setTimeoutFunc, opts.slideShowDelay);
				}
				stopTimer = function(jObj) {
					clearTimeout(jObj.slideShowTimer);
				}
				// play/pause
				$('a.btn-galleryPlay, a.btn-galleryPause', jObj).click(function() {							
					if ($(this).hasClass('btn-galleryPlay') === true) {
						$(this).removeClass('btn-galleryPlay').addClass('btn-galleryPause');
						playTheSlideShow(jObj, carousel);
					} else if ($(this).hasClass('btn-galleryPause') === true) {
						$(this).removeClass('btn-galleryPause').addClass('btn-galleryPlay');
						stopTimer(jObj);
					}							
			        return false;
			    });
				// goto the first item
				$('a.btn-gallerySpecial', jObj).click(function() {
					carousel.scroll(jQuery.jcarousel.intval(imgCount-2));
			        return false;
			    });
				// goto the first item
				$('a.btn-galleryGoToStart', jObj).click(function() {
					carousel.scroll(jQuery.jcarousel.intval(1));
			        return false;
			    });
				// goto the previous item
			    $('a.btn-galleryPrevious', jObj).click(function() {
			        carousel.prev();
			        return false;
			    });
				// goto the next item
			    $('a.btn-galleryNext', jObj).click(function() {
					carousel.next();
			        return false;
			    });
				// goto the last item
				$('a.btn-galleryGoToEnd', jObj).click(function() {
					carousel.scroll(jQuery.jcarousel.intval(carousel.size()));
			        return false;
			    });							
			};
			
			setTimer = function(jObj,carousel) {
				var setTimeoutFunc = function () { playTheSlideShow(jObj, carousel);};
				jObj.slideShowTimer = setTimeout(setTimeoutFunc, opts.slideShowDelay);
			}
			stopTimer = function(jObj) {
				clearTimeout(jObj.slideShowTimer);
			}
			slideShowHandler = function(nextElem, jObj, carousel) {
				$('div.itemBox-imageShow li.active', jObj).removeClass('active');
				$(nextElem).parent().addClass('active');
				var imgFullPath = $(nextElem).attr('href');
				var imgAltText	= $(nextElem).find('img').attr('alt');				
				if ($('div.cell-01 .itemBox-image img:visible', jObj).length > 0) {
					$('div.cell-01 .itemBox-image img:visible', jObj).fadeOut('fast', function() {
						$('div.cell-01 .itemBox-image', jObj).html('').css('background', '#FAF9F5 url(http://www.rewe.de/image/ppm/loader.gif) no-repeat 50% 50%');
						var img 	= new Image();
						$(img).load(function (){
							$(this).hide();
							$('div.cell-01 .itemBox-image', jObj).append($(this));
							var imgHeight = $(this).height();							
							if (imgHeight > 0 && imgHeight < 420) {
								var newMarginTop = '-'+(imgHeight/2)+'px';
								var cssObj = {
									position: 'relative',
									top: '50%',
									marginTop: newMarginTop
								}
								$(this).css(cssObj);
							}
							$(this).fadeIn('fast');
							$('div.cell-01 .itemBox-image').css('background', '#FAF9F5');
							
							if (typeof carousel === 'object' && carousel !== '') {
								setTimer(jObj, carousel);
							}
						}).error(function(){
							$('div.cell-01 .itemBox-image', jObj).append('<b>Das Bild kann leider nicht angezeigt werden.</b>');
							$('div.cell-01 .itemBox-image').css('background', '#FAF9F5');
							if (typeof carousel === 'object' && carousel !== '') {
								setTimer(jObj, carousel);
							}
						}).attr('src', imgFullPath);
					});
				} else {
					$('div.cell-01 .itemBox-image', jObj).html('').css('background', '#FAF9F5 url(http://www.rewe.de/image/ppm/loader.gif) no-repeat 50% 50%');
					var img = new Image();
					$(img).load(function (){
						$(this).hide();
						$('div.cell-01 .itemBox-image', jObj).append($(this));
						var imgHeight = $(this).height();							
						if (imgHeight > 0 && imgHeight < 420) {
							var newMarginTop = '-'+(imgHeight/2)+'px';
							var cssObj = {
								position: 'relative',
								top: '50%',
								marginTop: newMarginTop
							}
							$(this).css(cssObj);
						}
						$(this).fadeIn('fast');
						$('div.cell-01 .itemBox-image').css('background', '#FAF9F5');
						if (typeof carousel === 'object' && carousel !== '') {
							setTimer(jObj, carousel);
						}
					}).error(function(){
						$('div.cell-01 .itemBox-image', jObj).append('<b>Das Bild "'+imgFullPath+'" kann leider nicht angezeigt werden.</b>');
						$('div.cell-01 .itemBox-image').css('background', '#FAF9F5');
						if (typeof carousel === 'object' && carousel !== '') {
							setTimer(jObj, carousel);
						}
					}).attr('src', imgFullPath);
				}
				$('div.cell-01 .itemBox-caption').text(imgAltText);
			}			
			// thumbnail-click to enlarge
			$('div.itemBox-imageShow a', jObj).click(function() {
				var nextElem = $(this);
				slideShowHandler(nextElem, jObj, '');
				return false;
			});
			// start onload with the first thumbnail
			$('div.itemBox-imageShow a:first', jObj).click();
		});
	}
})(jQuery);

// M509 - Formulare
function ppmFX_509()
{
	// Formulare in der Seite finden
	$('div.M509 form').each(function()
	{
		// DatePicker hinzufügen und CSS-Klasse wechseln
		// bei allen input-Feldern deren "name" mit "tag" endet
		$(this).find('input[name$="tag"]').each(function()
		{
			$(this).val('');
			$(this).parent().removeClass('itemBox-formTextfield');
			$(this).parent().addClass('itemBox-formDatefield');
			$(this).datepicker();
		});		
		
		// Aktion bei versenden des Formulars
		$(this).submit(function()
		{
			// Input-Felder generieren
			$(this).find('div.btn-formSubmit')
				.append('<input type="hidden" name="actionType" value="ajax" />')
				.append('<input type="hidden" name="formURL" value="'+window.location.href+'" />');
			
			// Gewinnspiel Antwort Url-Kodieren
			//var inputValue = $('input[name=gewinnspiel]:checked').val();			
			//$('input[name=gewinnspiel]:checked').val(encodeURI(inputValue));
			
			var ajaxManager		= $.manageAjax({manageType: 'abortOld', maxReq: 1, blockSameRequest: true});
			var serializeForm	= $(this).serialize();
			var currentObj		= $(this);
			
			ajaxManager.add(
			{
				url: '/mein-markt/php/operator.php',
				type: 'POST',
				dataType: 'xml',
				data: serializeForm,
				success: function(xml)
				{							
					// Fehlerklassen zurücksetzen
					currentObj.find('div.error').removeClass('error');
					
					// Fehlermeldungen zurücksetzen
					currentObj.find('div.errorText').remove();
					
					// prüfen ob alles funktioniert hat
					if ($(xml).find('success').length == 1 )
					{
						$msg = $(xml).find('success').text();
						parentObj 		= currentObj.parent();
						parentObjHeight = parentObj.height();
						
						// Inhalt entfernen
						currentObj.slideUp('slow', function() {
							// neuen Inhalt hinzufügen
							parentObj.html($msg);
						});
					}
					else
					{				
						$(xml).find('item').each(function()
						{
							var parentLevel = false;
							var $item		= $(this);
							var name		= $item.find('name').text();
							var error		= $item.find('error').text();
							
							if (name != '' && error != '')
							{
								if (name == 'textfeld')
								{
									elemType		= 'textarea';
									errorAfterElem	= 'itemBox-formTextarea';
								}
								else if (name == 'teilnahme')
								{
									elemType		= 'input';
									errorAfterElem	= 'itemBox-formAnswer:last';
								}
								else
								{
									elemType		= 'input';
									errorAfterElem	= 'itemBox-formAddition';
								}
								
								var parentElem = currentObj.find(elemType+'[name^="'+name+'"]').parent().parent();
								
								parentElem
									.addClass('error')
									.css('height', 'auto')
									.find('div.'+errorAfterElem)
									.after('<div class="errorText typeFace-formAddition" style="display: none;">'+error+'</div>');
								
								parentElem.find('div.errorText')
									.fadeIn('slow')
									.animate({opacity: 1.0}, 3000);
							}
						});
					}
				}
			})
			
			return false;
		})
	});
}

// Marktinfo-iframe im Headbereich erzeugen
function createMarktInfo()
{
	if (typeof marktID == 'number' && isNaN(marktID) === false)
	{
		if (document.getElementById('rewe_markt'))
		{
			var elem		= document.getElementById('rewe_markt');
			elem.innerHTML	= '<iframe x="y" src="/mein-markt/php/getMarktInfo.php?marktID='+marktID+'" scrolling="no" frameborder="0" style="border: 0px none; background-color: transparent; width: 340px; height: 80px; overflow: hidden;" allowtransparency="true"></iframe>';	
		}
	}
	else
	{
		if (document.getElementById('rewe_markt')) 
		{
			var elem 		= document.getElementById('rewe_markt');
			elem.innerHTML 	= '<div id="marktsuche_2"><div class="btn-marktsuche typeFace-button"><a href="index.php?id=marktsuche" title="Markt suchen">Markt suchen</a></div></div>';
		}
	}
}

// MarktID aus Cookie auslesen
function getmktcookie()
{
	var lf = "\n";
	var CookieString = document.cookie;
	var CookieSet = CookieString.split (';');
	var SetSize = CookieSet.length;
	var CookiePieces
	var ReturnValue = "";
	var x = 0;
	for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++)
	{
		CookiePieces = CookieSet[x].split ('=');
		if (CookiePieces[0].substring (0,1) == ' ')
		{
			CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
		}
		if (CookiePieces[0] == 'rewe_selectedmarket')
		{
			ReturnValue = CookiePieces[1];
		}
	}
	return ReturnValue;
}

// prüft ob ein sprechender Öffnungszeitensatz vorhanden ist
function isNoNaturalPhraseForOpeningTimesAvailable(elem) {
	var elem = $(elem+':empty').size();
	// wenn elem = 1, dann wurde ein leeres Element gefunden
	if (typeof elem === 'number' && elem === 1) {
		return true;
	}
	return false;
}

// aktuelle Öffnungszeiten für den Tag als Satz
function createNaturalPhraseForActualOpeningTimes(elem)
{
	// aktuelles Datum holen
	var currentDate		= new Date();
	// aktuellen Wochentag bestimmen
	var weekdayNumber	= currentDate.getDay();
	// Wochentagsnamen festlegen
	var weekdayNames	= new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag');
	
	
	// prüfen ob den aktuellen Wochentag Daten hinterlegt sind
	if (typeof mtTimeTable != 'undefined' && isWorkableData(mtTimeTable[weekdayNames[weekdayNumber]]) === true)
	{
		// prüfen ob der Markt heute offen hat
		if (isMarketNotClosed(mtTimeTable[weekdayNames[weekdayNumber]]) === true) 
		{
			return 'Heute ge&ouml;ffnet von ' + formatOpeningTimes(mtTimeTable[weekdayNames[weekdayNumber]]['von'])+ '-'+ formatOpeningTimes(mtTimeTable[weekdayNames[weekdayNumber]]['bis'])+' Uhr';
		}
		else 
		{
			// nächsten Wochentag auswählen
			weekdayNumber++;
			
			// prüfen ob den aktuellen Wochentag Daten hinterlegt sind
			if (isWorkableData(mtTimeTable[weekdayNames[weekdayNumber]]) === true) 
			{
				// prüfen ob der Markt heute offen hat
				if (isMarketNotClosed(mtTimeTable[weekdayNames[weekdayNumber]]) === true) 
				{
					return 'Morgen wieder ab ' +formatOpeningTimes(mtTimeTable[weekdayNames[weekdayNumber]]['von'])+ '-' +formatOpeningTimes(mtTimeTable[weekdayNames[weekdayNumber]]['bis'])+' Uhr ge&ouml;ffnet';
				}
				// ansonstn prüfen wann der Markt als nächstes wieder offen hat
				else 
				{
					// jeden Wochentag durchgehen
					for (i = 0; i < 7; i++)
					{
						// prüfen ob den aktuellen Wochentag Daten hinterlegt sind
						if (isWorkableData(mtTimeTable[weekdayNames[weekdayNumber]]) === true) 
						{
							// prüfen ob der Markt heute offen hat
							if (isMarketNotClosed(mtTimeTable[weekdayNames[weekdayNumber]]) === true) 
							{
								return 'Am '+weekdayNames[weekdayNumber]+' wieder ab '+formatOpeningTimes( mtTimeTable[weekdayNames[weekdayNumber]]['von'])+'-'+formatOpeningTimes(mtTimeTable[weekdayNames[weekdayNumber]]['bis'])+' Uhr ge&ouml;ffnet';
							}
						}
						
						// nächsten Wochentag auswählen
						weekdayNumber++;
						
						// am Ende der Woche wieder zum Anfang springen
						if (weekdayNumber > 6)
						{
							weekdayNumber = 0;
						}
						
					}
				}
			}
		}	
	}
}

// prüfen ob vom Typ object
function isObject(data)
{
	if (typeof data == 'object') 
	{
		return true;
	}
	return false
}

// prüfen ob vom Typ string
function isNotUndefined(data)
{
	if (typeof data != 'undefined') 
	{
		return true;
	}
	return false
}

// prüfen ob nicht leer
function isNotEmpty(data)
{
	if (data != '')
	{
		return true;
	}
	return false;		
}

// prüfen ob weiterverarbeitbare Daten vorhanden sind
function isWorkableData(data)
{
	if (isObject(data) === true)
	{
		if (isNotUndefined(data['von']) === true && isNotEmpty(data['von']) === true && isNotUndefined(data['bis']) === true && isNotEmpty(data['bis']) === true)
		{
			return true;
		}
	}			
	return false;
}

// pürfen ob der Markt geöffnet hat
function isMarketNotClosed(data) {
	//if ((data['von'] != '2400' && data['bis'] != '2400') && (data['von'] != '0' && data['bis'] != '0'))
	if ((data['von'] == '2400' && data['bis'] == '2400') || (data['von'] == '0' && data['bis'] == '0')) {
		return false;
	}
	else {	
		return true;
	}
}

// Uhrzeit formatieren
function formatOpeningTimes(time)
{
	// prüfen ob Uhrzeit dreistellig ist
	if (time.length == 3)
	{
		// prüfen ob eine Minuten-Angabe nötig ist
		if (time.substring(1,3) == '00')
		{
			// Uhrzeit ohne Minuten-Angabe
			time = time.substring(0,1);
		}
		else
		{
			// Uhrzeit mit Minuten-Angabe und Trennzeichen
			time01	= time.substring(0,1);
			time02	= time.substring(1,3);
			time	= time01+':'+time02;
		}
	}
	// prüfen ob Uhrzeit vierstellig ist
	else if (time.length == 4)
	{
		// prüfen ob eine Minuten-Angabe nötig ist
		if (time.substring(2,4) == '00')
		{
			// Uhrzeit ohne Minuten-Angabe
			time = time.substring(0,2);
		}
		else
		{
			// Uhrzeit mit Minuten-Angabe und Trennzeichen
			time01	= time.substring(0,2);
			time02	= time.substring(2,4);
			time	= time01+':'+time02;
		}
	}
	
	return time;
}


