﻿
var freeplacesCache = new Array();

function handleAjaxRequest(thedata) {
	$.ajax({
		type: "GET",
		url: theurl,
		data: thedata,
		async: false,
		dataType: "text",
		success: function(obj){
			// Whitespaces aus der AJAX-Antwort entfernen:
			obj = obj.replace( /\s+/g, "");
			
			var days = obj.split(",")
			if (days.length == 0) {
				value = null
			} else {
				var val = new Array()
				for( var i = 0; i < days.length; i++) {
					var val_ = days[i]
					if (val_ == null || jQuery.trim(val_) == "" ) {
						val[i] = null
					} else {
						var days_ = val_.split(";")			   	 
						if (days_ == null || days_.length == 0) {val[i] = new Array(0)}
						else {val[i] = days_}
					}
				}
				value = val
			}
		}
	});
	return value;	
}	

function getMaxPlaces(year, month, day, time) {
	//var index = (isearly) ? 0 : 1
	var month_ = month + 1
	var thedata = "mode=maxplaces&year=" + year + "&month=" + month_ + "&day=" + day + "&index=" + time
	return handleAjaxRequest(thedata)  	
}

function getEventId(year, month, day, time) {
	//var index = (isearly) ? 0 : 1
	var month_ = month + 1
	var thedata = "mode=id&year=" + year + "&month=" + month_ + "&day=" + day + "&index=" + time
	return handleAjaxRequest(thedata)  
}

function getFreePlaces(year, month) {
	var key = year + "" + month;
	var value = freeplacesCache[key];
	if (value == null) {
		var thedata = "mode=places&year=" + year + "&month=" + month;
		value = handleAjaxRequest(thedata);
		//alert( value );
		freeplacesCache[key] = value;
	}
	return value
}	

function isGreaterZero(val) {return val != null && jQuery.trim( val ) != '' && val > 0}	

function submitForm(year, month, day, time, freeplaces) {
	var idString = getEventId(year, month, day, time)
	var maxPlaces = getMaxPlaces(year, month, day, time);
	if ( freeplaces > maxPlaces ) freeplaces = maxPlaces;
	$("#calendarFormYear").val(year)
	$("#calendarFormMonth").val(month)
	$("#calendarFormDay").val(day)
	$("#calendarFormTime").val(time)
	$("#calendarFormId").val(idString)
	$("#calendarFormFreeplaces").val(freeplaces)
	$("#calendarForm").submit()
}

function formatTime( time ) {
	var times = time.split( "-" );
	var retVal = "";
	var times_ = times[0].split(":");
	retVal += times_[0] + "." + times_[1] + " - ";
	times_ = times[1].split(":");
	retVal += times_[0] + "." + times_[1];
	return retVal;
}

function buildText( time, places, year, month, day ) {
	var retVal = "<p>";
	retVal += "<strong>" + formatTime(time) + " Uhr - F&uuml;hrung</strong><br/>";
	if ( places == 1 ) {
		retVal += "noch " + places + " Platz frei";
	} else if ( places > 0 ) {
		retVal += "noch " + places + " Pl&auml;tze frei";
	} else {
		retVal += "kein Platz mehr frei";
	}
	if ( places > 0 ) {
		retVal += "<br/><a href=\"javascript:submitForm(" + year + ", " + month + ", " + day + ", '" + time + "', " + places + ");\">Anmelden</a></p>";
	}
	retVal += "</p>";
	return retVal;
}

$(document).ready(function() {
	$('.calendarContainer .calendarBox')
	.datePicker({
		inline:true,
		showYearNavigation:false,
		createButton:false,
		renderCallback:function($td, thisDate, month, year){				
			tmp_day = thisDate.getDate()
			tmp_actMonth = month + 1
			tmp_thisDateMonth = thisDate.getMonth() + 1
			tmp_week_day = thisDate.getDay()
			if (tmp_actMonth != tmp_thisDateMonth) { //only the days of the current month are shown
				$td.empty()
			} else {
				var jsonValues = getFreePlaces( year, month + 1 )
				var currentDay = null
				if (jsonValues != null && jsonValues[ tmp_day - 1 ] != null) { 
					currentDay = jsonValues[ tmp_day - 1 ]
				}
				if ( currentDay == null || currentDay.length == 0 ) { 
					/* No free places left */ 
					$td.addClass('calNotFree')
				} else {
					//alert( "Array: " +  currentDay.length );					
					var tooltipText = ""
					if (tmp_week_day == 6) {
						$td.addClass( 'calFive');
					} else if (tmp_week_day == 5) {
						$td.addClass( 'calFiftyFive' );
					} else {
						$td.addClass( 'calFifty');
					}
					
					var isfree = false;
					//Die Werte ( {Startzeit} - {Endzeit} = {Plaetze} ) splitten 
					var currentDays = new Array();
					for( var index = 0; index < currentDay.length; index++ ) {
						//alert( currentDay[index] );						
						var items = currentDay[index].split("=");
						currentDays[ items[0] ] = items[1];
					}
					
					for( var itemKey in currentDays ) {
						var itemValue = currentDays[ itemKey ];
						tooltipText += buildText( itemKey, itemValue, year, month, tmp_day );						
						if (isGreaterZero( itemValue )) { 
							isfree = true
						}
					}
					
					if (isfree) {
						$td.addClass( 'calFree')
					}
					
					/*
					if (currentDay.length == 1) { //Free places only in the morning
						if (isGreaterZero( currentDay[0])) {
							isfree = true
							tooltipText += buildText( true, currentDay[0], year, month, tmp_day );
						} else {
							tooltipText += buildText( true, 0, year, month, tmp_day );
						}
					} else {
						if ( !isGreaterZero(currentDay[0]) && !isGreaterZero(currentDay[1])) {
							**No free places in the morning and no free places in the afternoon
						} else {					
							if (isGreaterZero(currentDay[0])) { 
							**Free places in the morning
								isfree = true;
								tooltipText += buildText( true, currentDay[0], year, month, tmp_day );
							} else {
								tooltipText += buildText( true, 0, year, month, tmp_day );
							}
							if (isGreaterZero( currentDay[1])) { 
							**Free places in the afternoon
								isfree = true;
								tooltipText += buildText( false, currentDay[1], year, month, tmp_day );
							} else {
								tooltipText += buildText( false, 0, year, month, tmp_day );
							}
						}
					}*/
					
					if ( tooltipText != "" ) {
						tooltipText = "<div class='tooltip'>" + tooltipText + "</div>"
						$td.html( $td.html() + tooltipText )
						$td.hoverIntent(function () {
							$td.addClass('hover')
							$td.children().children("div.tooltip").fadeIn("fast")
						}, function () {
							$td.children().children("div.tooltip").fadeOut("fast", function callback(){
							$td.removeClass('hover')	
							})
						})						 
					}
				}
				$td.html('<div class="innerTd">' + $td.html() + '</div>')
			}
		}
	})
	.bind('dpMonthChanged', function(event, displayedMonth, displayedYear) {getFreePlaces(displayedYear, displayedMonth) /* Preload the available places */ })
})
