

















/*
* Render Date picker
*/
(function($) {
$.ti.pickDates = $.prototype = {

	html:	$([	'<div id="swapableContent">',
					'<h2><img src="/shared/resource/images/itinerary_planner/de/text/overlay-headings/pick-dates.png" alt="W&auml;hlen Sie Ihre Reisedaten." height="28"/></h2>',
					'<p>Sie reisen nach Irland und kennen Ihre Reisedaten bereits? Vielleicht sind Sie unsicher, wann Sie reisen sollen, oder Sie wissen bisher nur, in welchem Monat Sie reisen &#8212; Dann w&auml;hlen Sie einfach die gew&uuml;nschten Optionen aus und der Reiseplaner empfiehlt Ihnen Eintr&auml;ge, die Sie f&uuml;r die Reise ausw&auml;hlen k&ouml;nnen. Viel Spa&szlig;!</p>',
					'<form action="" method="" id="pickDates">',
						'<fieldset>',
							'<h3 class="section">Wann m&ouml;chten Sie reisen?</h3>',
							'<div class="section">',
								'<label for="notSure">',
									'<input type="radio" name="datePicker" id="notSure" class="radio" value="notSure" />',
								'Ich wei&szlig; es noch nicht. </label>',
							'</div>',
							'<div class="section">',
								'<label for="exactDate" id="exactDateLabel">',
									'<input type="radio" name="datePicker" id="exactDate" class="radio" value="exactDate" />',
								'Ich wei&szlig; die genauen Daten. </label>',
								'<div id="exactDateToggler" style="display:none;">',
									'<p>Sobald Sie Ihre exakten Reisedaten eingegeben haben, ist der Reiseplaner auf Sie und Ihre Irlandreise zugeschnitten.</p>',
									'<div id="exactDates">',
										'<div class="date">',
											'<label for="startDate">Anreisedatum:',
												'<input type="text" id="startDate" />',
											'</label>',
										'</div>',
										'<div class="date">',
											'<label for="endDate">R&uuml;ckreisedatum:',
												'<input type="text" id="endDate" />',
											'</label>',
										'</div>',
									'</div>',
								'</div>',
							'</div>',
							'<div class="section lastSection">',
								'<label for="timeOfYear" id="timeOfYearLabel">',
									'<input type="radio" name="datePicker" id="timeOfYear" class="radio" value="timeOfYear" />',
								'Ich wei&szlig; die Jahreszeit:</label>',
								'<div id="timeOfYearToggler" style="display:none;">',
									'<p>W&auml;hlen Sie die Jahreszeit aus, in der Sie nach Irland reisen m&ouml;chten, und wir w&auml;hlen Angebote und Empfehlungen passend zu Ihren W&uuml;nschen aus.</p>',
									'<div id="months">',
										'<ul id="monthList"></ul>',
									'</div>',
									'<div class="slider">',
										'<div id="prevYear" class="date-nav"><img src="/shared/resource/images/itinerary_planner/buttons/prev-next-months.png" width="36" height="36" alt="vorherige" /></div>',
										'<div id="dateSlider"></div>',
										'<div id="nextYear" class="date-nav"><img src="/shared/resource/images/itinerary_planner/buttons/prev-next-months.png" width="36" height="36" alt="n&auml;chste" /></div>',
									'</div>',
								'</div>',
							'</div>',
						'</fieldset>',
						'<input type="image" class="button" src="/shared/resource/images/itinerary_planner/de/buttons/save.png" alt="Speichern" height="22" id="saveDates"/>',
					'</form>',
				'</div>'
			].join('')),

	currentDate:	new Date(),
	currentDay: 0,
	currentMonth: 0,
	currentYear: 0,

	setUpPicker: function() {

		// Set current day, month and year
		$.ti.pickDates.currentDay = $.ti.pickDates.currentDate.getDate();
		$.ti.pickDates.currentMonth = $.ti.pickDates.currentDate.getMonth();
		$.ti.pickDates.currentYear = $.ti.pickDates.currentDate.getFullYear();

		// Kill date pickers on close
		$('#close').unbind('click.closePopup');
		$('#close').bind('click.closePopup', function() {
			$("#startDate").removeClass('hasDatepicker').datepicker("destroy");
			$("#endDate").removeClass('hasDatepicker').datepicker("destroy");
		});

		// Add existing start date if present
		if($.ti.tripData.trip.tripStartDate) {
			$("#startDate").val($.ti.tripData.trip.tripStartDate);
		}
		// Add existing end date if present
		if($.ti.tripData.trip.tripEndDate) {
			$("#endDate").val($.ti.tripData.trip.tripEndDate);
		}

		// Create date picker "from" calender
		$("#startDate").removeClass('hasDatepicker').datepicker({
			minDate:	$.ti.pickDates.currentDate,
			onSelect:	function() {
								$("#endDate").datepicker('option', 'minDate', $("#startDate").datepicker('getDate'));
						},
			dateFormat: 'yy-mm-dd',
			constrainInput: true,
			showOtherMonths: true
		});

		// Create date picker "to" calender
		$("#endDate").removeClass('hasDatepicker').datepicker({
			minDate: $.ti.pickDates.currentDate,
			defaultDate: +1,
			onSelect: function() {
								$("#startDate").datepicker('option', 'maxDate', $("#endDate").datepicker('getDate'));
						},
			dateFormat: 'yy-mm-dd',
			constrainInput: true,
			showOtherMonths: true
		});

		// Hide initial state of datepicker before we interact with it.
		$('#ui-datepicker-div').hide();

		$.ti.pickDates.accordion();
		$.ti.pickDates.calculateMonths();
		$.ti.pickDates.setMonthCarousel();

		$.ti.pickDates.monthListItems = $('#monthList > li');

		$($.ti.pickDates.monthListItems).removeClass('active');
		$($.ti.pickDates.monthListItems[0]).addClass('active');

		// Create date slider
		$("#dateSlider").slider({
			animate: true,
			min:0,
			max:11,
			slide: function(event, ui) {
				$($.ti.pickDates.monthListItems).removeClass('active');
				$($.ti.pickDates.monthListItems[ui.value]).addClass('active');
			}
		});

		// Add save event
		$('#saveDates').bind('click.saveDates', function(event){
			
            //save toggle code
            changes = 1;
            
            event.preventDefault();

			switch($('input[name=datePicker]:checked').attr('id')) {
				case 'exactDate':	$.ti.pickDates.checkExact();
									break;
				case 'timeOfYear':	$.ti.pickDates.setMonth();
									break;
				case 'notSure':		$.ti.pickDates.setVague();
									break;
			}

		});
	},

	checkExact: function() {
		$.ti.validate.check('#exactDates', {
			rules: {
				startDate: {
					"required": 'Anreisedatum erforderlich',
					"date": 'G&uuml;ltige Daten ausw&auml;hlen'
				},
				endDate: {
					"required": 'R&uuml;ckreisedatum erforderlich',
					"date": 'G&uuml;ltige Daten ausw&auml;hlen',
					"notLess": [$('#startDate').val(), 'R&uuml;ckreisedatum kann nicht vor Anreisedatum liegen.']
				}
			},
			success: function() {$.ti.pickDates.setExact();}
		});
	},

	setExact: function() {
		// Kill any previous instance of date pickers
		$("#startDate").removeClass('hasDatepicker').datepicker("destroy");
		$("#endDate").removeClass('hasDatepicker').datepicker("destroy");

		// Set start, end and duration values
		$.ti.tripData.trip.tripStartDate = $('#startDate').val();
		$.ti.tripData.trip.tripEndDate = $('#endDate').val();
		$.ti.pickDates.setDuration();

		// Update dates and close popup
		$.ti.pickDates.showDates();
		$.ti.popup.close();

		$.ti.createTripCalendar.resetCalender();
		$.ti.panel.datesChanged = 'exact_dates';
	},

	// Calculate the trip length in days
	setDuration: function() {
		var start, end;
		// Get start and end date objects n.b. '-' changed to '/' for IE
		start = new Date($.ti.tripData.trip.tripStartDate.replace(/-/g, '/'));
		end = new Date($.ti.tripData.trip.tripEndDate.replace(/-/g, '/'));

		// Calculate difference in days
		$.ti.tripData.trip.tripDuration = ((end - start) / 86400000) + 1; // (1000 * 60 * 60 * 24) = 1 day;
	},

	// Set dates based on selection of a month from slider
	setMonth: function() {
		var item, month, year, nextWeek, nextWeekDay, nextWeekMonth, nextWeekYear;

		item = $('li.active', '#monthList');
		month = parseInt($(item).attr('rel'), 10);
		year = parseInt($('span', item).text(), 10);

		if(month === this.currentMonth && year === this.currentYear) {
			// insert leading zero on month if necessary
			month = $.ti.utils.padNumber(month + 1);

			// Set startDate
			$.ti.tripData.trip.tripStartDate = year + '-' + month + '-' + this.currentDay;
		} else {
			// insert leading zero on month if necessary
			month = $.ti.utils.padNumber(month + 1);

			// Set start and end dates
			$.ti.tripData.trip.tripStartDate = year + '-' + month + '-' + "01";
		}

		// Set EndDate
		var lastDate = $.ti.pickDates.getLastDate(month, year);
		$.ti.tripData.trip.tripEndDate = year + '-' + month + '-' + lastDate;

		// Seet duration
		$.ti.pickDates.setDuration();

		// Update dates and close popup
		$.ti.pickDates.showDates();
		$.ti.popup.close();
		$.ti.createTripCalendar.resetCalender();
		$.ti.panel.datesChanged = 'time_of_year';
	},

	getLastDate: function(month, year) {
		var dd = new Date(year, month, 0);
		return dd.getDate();
	},

	// Remove start and end dates and set duration to "7" for "not sure" users
	setVague: function() {
		$.ti.tripData.trip.tripStartDate = null;
		$.ti.tripData.trip.tripEndDate = null;
		$.ti.tripData.trip.tripDuration = 7;

		// Update dates and close popup
		$.ti.pickDates.showDates();
		$.ti.popup.close();
		$.ti.createTripCalendar.resetCalender();
		$.ti.panel.datesChanged = 'not_sure';
	},

	startMonth: new Date().getMonth(),

//Jan => Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

	monthNames: {
		 0: 'Jan',
		 1: 'Feb',
		 2: 'Marz',
		 3: 'Apr',
		 4: 'Mai',
		 5: 'Juni',
		 6: 'Juli',
		 7: 'Aug',
		 8: 'Sept',
		 9: 'Okt',
		10: 'Nov',
		11: 'Dez'
	},

	dayNames: {
		0: 'Sun',
		1: 'Mon',
		2: 'Tue',
		3: 'Wed',
		4: 'Thu',
		5: 'Fri',
		6: 'Sat'
	},

	accordion: function() {
		$('input[name=datePicker]').bind('click.toggles', function(event) {
			switch(event.target.id) {
				case 'notSure':	$('#exactDateToggler').slideUp(500);
								$('#timeOfYearToggler').slideUp(500);
								break;
				case 'exactDate':	$('#exactDateToggler').slideDown(500);
									$('#timeOfYearToggler').slideUp(500);
									break;
				case 'timeOfYear':	$('#exactDateToggler').slideUp(500);
									$('#timeOfYearToggler').slideDown(500);
									break;
			}
		});
	},

	calculateMonths: function() {
		if(!$('#monthList > li').length) {
			var dates = {
				count: 0,
				year: this.currentDate.getFullYear(),
				month: this.startMonth
			};

			for (dates.count = 0; dates.count < 12; dates.count += 1) {
				$('#monthList').append($('<li rel="' + dates.month + '">' + this.monthNames[dates.month] +'<span>' + dates.year + '</span></li>'));
				dates.month = (dates.month + 1);
				if(dates.month === 12) {
					dates.year = (dates.year + 1);
					dates.month = 0;
				}
			}
		}
	},

	monthSliderView: 0,
	monthSliderLength: 0,

	setMonthCarousel: function() {
		$('#nextYear > img').bind('click.nextYear', function() {
			if($.ti.pickDates.monthSliderView === $.ti.pickDates.monthSliderLength) {
				$.ti.pickDates.createTwelveMonths($.ti.pickDates.monthSliderView +1);
				$.ti.pickDates.monthSliderLength = ($.ti.pickDates.monthSliderLength + 1);
			}
			$.ti.pickDates.monthSliderView = ($.ti.pickDates.monthSliderView + 1);
			$('#monthList').animate({"left":"-=468px", duration: 2000, easing: 'easeout'});
			$.ti.pickDates.resetSlider(12);
		});
		$('#prevYear > img').bind('click.prevYear', function() {
			if($.ti.pickDates.monthSliderView > 0) {
				$.ti.pickDates.monthSliderView = ($.ti.pickDates.monthSliderView - 1);
				$('#monthList').animate({"left":"+=468px", duration: 2000, easing: 'easeout'});
				$.ti.pickDates.resetSlider(-12);
			}
		});
	},

	resetSlider: function(operator) {
		var settings = {
			min: $('#dateSlider').slider('option', 'min') + operator,
			max: $('#dateSlider').slider('option', 'max') + operator,
			current: $('#dateSlider').slider('option', 'value') + operator
		};

		$.ti.pickDates.monthListItems = $('#monthList > li');

		$('#dateSlider').slider('option', {
				'min': settings.min,
				'max': settings.max,
				'value': settings.current
			});

		$($.ti.pickDates.monthListItems[(settings.current - operator)]).removeClass('active');
		$($.ti.pickDates.monthListItems[settings.current]).addClass('active');
	},

	createTwelveMonths: function(view) {
		var settings = {
			count: 0,
			month: $.ti.pickDates.currentDate.getMonth(),
			year: $.ti.pickDates.currentDate.getFullYear() + view
		};

		for(settings.count = 0; settings.count < 12; settings.count += 1) {
			$('#monthList').append($('<li rel="' + settings.month + '">' + this.monthNames[settings.month] + '<span>' + settings.year + '</span></li>'));
			settings.month = (settings.month + 1);
			if(settings.month === 12) {
				settings.year = (settings.year + 1);
				settings.month = 0;
			}
		}
	},

	// Render exact days date onto calender
	showDates: function() {
		var dates = {
			start: {
				obj: '',
				day: '',
				month: '',
				year: ''
			},
			end: {
				obj: '',
				day: '',
				month: '',
				year: ''
			},
			startString: '',
			endString: ''
		};

		function getDayMonthYear(date) {
			dates[date].day = dates[date].obj.getDate();
			dates[date].month = $.ti.pickDates.monthNames[dates[date].obj.getMonth()];
			dates[date].year = dates[date].obj.getFullYear();
		}

		if($.ti.tripData.trip.tripStartDate) {
			// Reformat dates with "/" instead of "-" for IE
			dates.startString = $.ti.tripData.trip.tripStartDate.replace(/-/g, '/');
			dates.endString = $.ti.tripData.trip.tripEndDate.replace(/-/g, '/');

			// Get start and end date objects
			dates.start.obj = new Date(dates.startString);
			dates.end.obj = new Date(dates.endString);

			// Get Start day month and year
			getDayMonthYear("start");

			// Clear old calender dates
			$('#calendarDates').empty();
			if($.ti.tripData.trip.tripDuration <= 1) {
				// Create single day date
				if ('cn'==='de')
				{
					$('#calendarDates').append('<span>'+dates.start.year+'</span> '+dates.start.month+' '+dates.start.day+'???planner.calendar.date???');
				}
				else
				{
					$('#calendarDates').append(dates.start.day + ' ' + dates.start.month + ' <span>' + dates.start.year + '</span>');
				}
			} else {
				// Get end day, month and year
				getDayMonthYear("end");

				if ('cn'==='de')
				{
					if(dates.start.year === dates.end.year) {
						$('#calendarDates').append('<span>'+dates.start.year+'</span> '+dates.start.month+dates.start.day+'???planner.calendar.date??? - '+dates.end.month+' '+dates.end.day+'???planner.calendar.date???');
					} else {
						$('#calendarDates').append('<span>'+dates.start.year+'</span> '+dates.start.month+dates.start.day+'???planner.calendar.date??? - <span>'+dates.end.year+'</span> '+dates.end.month+' '+dates.end.day+'???planner.calendar.date???');
					}
				}
				else
				{
					if(dates.start.year === dates.end.year) {
						// Create multiple day date within same year
						$('#calendarDates').append(dates.start.day + ' ' + dates.start.month + ' - ' + dates.end.day + ' ' + dates.end.month + ' <span>' + dates.end.year + '</span>');
					} else {
						// Create multiple day date across two years
						$('#calendarDates').append(dates.start.day + ' ' + dates.start.month + ' <span>' + dates.start.year + '</span> - ' + dates.end.day + ' ' + dates.end.month + ' <span>' + dates.end.year + '</span>');
					}
				}
			}
		} else {
			dayN='Tag ';
			if (dayN.indexOf('#')>0)
				$('#calendarDates').text(dayN.replace(/#/,''+(1))+' - '+dayN.replace(/#/,''+($.ti.tripData.trip.tripDuration)));
			else
				$('#calendarDates').text(dayN+' 1 - '+dayN+' '+$.ti.tripData.trip.tripDuration);
		}
	}

};
})(jQuery);
