/**
 * Scripts needed for communication between various
 * "fromDate" and "toDate" handling parts
 */

/**
 * jquery selector string matching all date input fields for either from or to dates
 */
var fromFields = '#Form_WannWasWo #Anreise, #FinderAnreise, #VerfeinernAnreise, input[name="vondatum"]';
var toFields = '#Form_WannWasWo #Abreise, #FinderAbreise, #VerfeinernAbreise, input[name="bisdatum"]';

// Whenever the user actively sets any datum, this status flag is set true
var isUserSet = true;

/**
 * To be called when the date setting of any of from or to has changed.
 * @param from
 * @param to
 * @return void
 */
function setWhen(from, to) {
	
	//console.log("setWhen(" + from + ", " + to + ")");
	$(fromFields).attr("value", from);
	$(toFields).attr("value", to);
	
	// Flashvars as global datekeeper
	flashvars.from = from;
	flashvars.to = to;
	
	// Modify all anchors containing dates
	parseAnchorDates();
	
	// make ajax calls on every defined element
	makeAjaxCalls();
    
    // change themes selection in WhenWhatWhere:
	setThemeVisibility();
	
	// switch season dependent element's visibility
	switchSeason(from);

}

/**
 * Passes changed dates to the header flash
 * @param from
 * @param to
 * @return void
 */
function setHeaderWhen(from, to) {
	isUserSet = true;
	setWhen (from, to);
	//var flash = ($.browser.msie)? window["header"] : document["header"];
    //if (flash) flash.setHeaderWhen(from,to);
}

function parseDate (datestr) {
	if (datestr === undefined) {
		var date = new Date();
		datestr = dateToString({year:date.getFullYear(), month:date.getMonth()+1, day:date.getDate()});
	}
	var dateobj = new Object();
	dateobj.year = parseInt(datestr.substr(datestr.length - 4), 10);
	dateobj.month = parseInt(datestr.substring(datestr.indexOf('.') + 1, datestr.lastIndexOf('.')), 10);
	dateobj.day = parseInt(datestr.substring(0, datestr.indexOf('.')), 10);
	dateobj.season = "winter";
	if (dateobj.month > 3) dateobj.season = "spring";
	if (dateobj.month > 5) dateobj.season = "summer";
	if (dateobj.month > 8) dateobj.season = "fall";
	if (dateobj.month > 10) dateobj.season = "winter";
	return dateobj;
}

function dateToString(to) {
	return to.day + "." + to.month + "." + to.year
}

/**
 * read all anchor tags and modify dates if appropriate
 */
function parseAnchorDates() {
	var re = /[0-9]+\.[0-9]+\.[0-9]+\/to\/[0-9]+\.[0-9]+\.[0-9]+/
	var repl = flashvars.from + "/to/" + flashvars.to;
	
	$('a').each (function () {
		var old = $(this).attr("href");
		if (old)
			$(this).attr("href", old.replace(re, repl));
	});
	
	$('form').each (function () {
		var old = $(this).attr("action");
		if (old)
			$(this).attr("action", old.replace(re, repl));	
	});
	
	$('a.datedisplay_from').text(flashvars.from);
	$('a.datedisplay_to').text(flashvars.to);
	
}

function increaseDateOneDay(to) {
	// Increase from date by 1 day
	to.day += 1;
	
	if (to.month == 2 && to.day > 28) {
		to.day = 1;
		to.month = 3;
	}
	if (to.day > 30 && (to.month == 4 || to.month == 6 || to.month == 9 || to.month == 11)) {
		to.day = 1;
		to.month += 1;
	}
	if (to.day > 31) {
		to.day = 1;
		to.month += 1;
	}
	if (to.month > 12) {
		to.month = 1;
		to.year += 1;
	}
	return to;
}

function switchSeason (datum) {
	var d = parseDate(datum);
	var season = d.season;
	//console.log(season);
	var seasons = ["spring", "summer", "fall", "winter"];
	/*for each (var s in seasons) {
		var display = (s == season)? "block" : "none";
		$('.' + s).css("display", display);
	}
*/

	seasons.each(function(){
		var display = (this == season)? "block" : "none";
		$('.' + s).css("display", display);
	});
	
}
	
/**
 * All datepicker fields have to pass changed values to any listeners, except the header flash
 */
$(document).ready (function() {
	
	// Initialize the isUserSet status flag;
	// If the from date equals today and the to date
	// equals today plus one year, we suspect that no
	// user manipulation yet has taken place.
	var from = parseDate($(fromFields).eq(0).val());
	var to = parseDate($(toFields).eq(0).val());
	var today = new Date();

	/*if (	from.day == to.day
			&& from.month == to.month
			&& parseInt(from.year, 10) == (parseInt(to.year, 10) - 1)
			&& today.getDate() == parseInt(from.day, 10)
			&& (today.getMonth() + 1) == parseInt(from.month, 10)
			&& today.getFullYear() == parseInt(from.year, 10)) {
		isUserSet = false;
		//console.log("isUserSet is false!");
	} else {
		isUserSet = true;
		//console.log("isUserSet is true!");
	}*/
		
//	var month = today.getMonth() + 1;
//	var from = today.getDate() + "." + month + "." + today.getFullYear();
	
	$(fromFields).change(function(){
		var fromstr = $(this).val();
		var from = parseDate(fromstr);
		
		var to = parseDate(flashvars.to);
		// if not explicitly set by the user, the end date is to be set
		// to startdate + one day
		if (!isUserSet) {
			to = increaseDateOneDay(from);
			flashvars.to = dateToString(to); 
			isUserSet = true;
		} else {
			if (from.year > to.year){
				flashvars.to = dateToString(increaseDateOneDay(from));
			} else if (from.year == to.year) {
				if (from.month > to.month) {
					flashvars.to = dateToString(increaseDateOneDay(from));
				} else if (from.month == to.month && from.day > to.day) {
					flashvars.to = dateToString(increaseDateOneDay(from));
				}
			}
		}
		setHeaderWhen(fromstr, flashvars.to);
	});
	
	$(toFields).change(function(){
		var tostr = $(this).val();
		var to = parseDate(tostr);
		var from = parseDate(flashvars.from);
				
		if (from.year > to.year){
			flashvars.from = tostr;
		} else if (from.year == to.year) {
			if (from.month > to.month) {
				flashvars.from = tostr;
			} else if (from.month == to.month && from.day > to.day) {
				flashvars.from = tostr;
			}
		}
		
		setHeaderWhen(flashvars.from, $(this).val());
	}).click(function(e){		
		var from = parseDate(flashvars.from);
		var to = increaseDateOneDay(from);
		
		var dateto = new Date();
		dateto.setDate(to.day);
		dateto.setMonth(to.month - 1);
		dateto.setYear(to.year);
		$(this).datepicker( 'setDate' , dateto);
	});
	
});
