/* ---------------------------------------------------------------------------------------------------- */
/* =fewo.detail.js */
/* ---------------------------------------------------------------------------------------------------- */

FEWO.detail = {};


/* -------------------------------------------------- */
/* =pics */

FEWO.detail.pics = {
	
	settings: {
		numberOfSlots: 2,
		slotSize: {x: 246, y: 158},
		gutterSize: 5
	},
	
	init: function () {
		this.container = $('detail-picture-gallery');
		this.element = this.container.getElement('ul');
		this.items = this.container.getElements('li');
		this.element.setStyle('width', this.items.length * (this.settings.slotSize.x + this.settings.gutterSize));
		
		this.fx = new Fx.Tween(this.element, {
			link: 'cancel',
			transition: 'sine:out'
		});
		
		this.buttons = {
			'prev': $('detail-picture-gallery-prev').addEvent('click', this.prev.bind(this)),
			'next': $('detail-picture-gallery-next').addEvent('click', this.next.bind(this))
		};		
		
		this.set(0);
	},
	
	prev: function () {
		this.set(this.currentIndex - 1);
	},
	
	next: function () {
		this.set(this.currentIndex + 1);
	},
	
	set: function (index) {
		if (index >= 0 && index <= this.items.length - this.settings.numberOfSlots) {
			this.currentIndex = index;
			this.fx.start('left', -((this.settings.slotSize.x + this.settings.gutterSize) * index));
			this.checkControls();
		}
	},
	
	checkControls: function () {
		this.buttons.prev.setStyle('display', (this.currentIndex == 0) ? 'none' : 'block');
		this.buttons.next.setStyle('display', (this.currentIndex == this.items.length - this.settings.numberOfSlots) ? 'none' : 'block');
	}
	
};


/* -------------------------------------------------- */
/* =location */

FEWO.detail.location = {
	
	init: function () {
		this.element = $('detail-options').getElement('.icon_map');
		if (!this.element) return false;
		this.element.addEvent('click', this.open.bindWithEvent(this.element));
	},
	
	open: function (event) {
		event.stop();
		window.open(this.href, 'location', 'width=800, height=700, toolbar=no');
	}
	
};


/* -------------------------------------------------- */
/* =availability */

FEWO.detail.availability = {
	
	options: {
		months: MXM.Date.Months,
		startDate: new Date()
	},
	
	init: function (options) {
		this.options = $merge(this.options, options);
		this.month.init(this.options);
		this.year.init(this.options);
	}	
	
};


FEWO.detail.availability.year = {
	
	options: {
	
	},
	
	init: function (options) {
		this.options = $merge(this.options, options);
		
		this.options.DisplayRange[0] = new Date(MXM.Date.extract(this.options.DisplayRange[0]));
		this.options.DisplayRange[1] = new Date(MXM.Date.extract(this.options.DisplayRange[1]));
		
		// set new startDate if startDate is passed by options but is an empty string
		if (this.options.startDate == '') {
		    this.options.startDate = new Date();
		}
		
		// set new startDate if startDate is passed by options but is an empty string
		if (this.options.selectedDate == '') {
		    this.options.selectedDate = new Date();
		}
			
		this.startDate = new Date(($type(this.options.startDate) == 'date') ? this.options.startDate.setDate(1) : MXM.Date.extract(this.options.startDate).setDate(1));
		this.selectedDate = new Date(($type(this.options.selectedDate) == 'date') ? this.options.selectedDate.setDate(1) : MXM.Date.extract(this.options.selectedDate).setDate(1));
		
		this.isInitialLoad = true;
			
		this.container = $('detail-calendar-year');
		this.items = this.container.getElements('.month');
		this.buttons = {
			prev: $('detail-calendar-year-prev'),
			next: $('detail-calendar-year-next')
		};
		this.buttons.prev.addEvent('click', this.prevYear.bind(this));
		this.buttons.next.addEvent('click', this.nextYear.bind(this));
		
		this.currentIndex = this.selectedDate.getMonth() - this.startDate.getMonth();
		if (this.currentIndex < 0) this.currentIndex += 12;
		this.renderYear();
	},
	
	prevYear: function () {
		this.startDate.setFullYear(this.startDate.getFullYear() - 1);
		this.selectedDate.setFullYear(this.selectedDate.getFullYear() - 1);
		this.renderYear();
	},
	
	nextYear: function () {
		this.startDate.setFullYear(this.startDate.getFullYear() + 1);
		this.selectedDate.setFullYear(this.selectedDate.getFullYear() +1);
		this.renderYear();
	},
	
	renderYear: function () {
		var tmpDate = new Date(this.startDate);
		this.dates = [];
		this.items.each(function (item, index) {
			this.dates.push(new Date(tmpDate));
			var element = item.getElement('a');
			element.set('text', FEWO.detail.availability.options.months[tmpDate.getMonth()].substring(0, 3) + ' ' + tmpDate.format('yy'));
			element.removeEvents('click');
			element.addEvent('click', this.setCurrent.pass(index, this));
			tmpDate.setNextMonth();
		}, this);
		this.setCurrent(this.currentIndex);
		this.checkControls();
	},
	
	setCurrent: function (index) {
		this.items[this.currentIndex].removeClass('active');
		this.currentIndex = index;
		this.items[this.currentIndex].addClass('active');
		this.selectedDate = new Date(this.dates[this.currentIndex]);
		if (this.isInitialLoad) {
			FEWO.detail.availability.month.setInitalAvailability(this.selectedDate);
			this.isInitialLoad = false;
		} else {
			FEWO.detail.availability.month.getAvailability(this.selectedDate);
		}
	},
	
	checkControls: function () {		
		var tmpDate = new Date(this.startDate);
		tmpDate.setFullYear(tmpDate.getFullYear() + 1);
		
		this.buttons.prev.setStyle('visibility', (MXM.Date.compare(this.startDate, this.options.DisplayRange[0], {accuracy: 'd', operator: '>'})) ? 'visible' : 'hidden');
		this.buttons.next.setStyle('visibility', (MXM.Date.compare(tmpDate, this.options.DisplayRange[1], {accuracy: 'd', operator: '<'})) ? 'visible' : 'hidden');
	}
	
};


FEWO.detail.availability.month = {
	
	init: function () {
		this.container = $('detail-calendar-month');
		this.items = this.container.getElements('.day');
		this.buttons = {
			'book': $('availability-book').getElement('input'),
			'contact': $('availability-contact').getElement('input')
		};
		this.buttons.book.addEvent('click', this.sendBookingRequest.bind(this));
		this.disableButton(this.buttons.book);
		this.bookingurl = null;
		
		this.buildContextMenu();
	},
		
	getAvailability: function (date) {
		this.selectedDate = date;
		new Request.JSON({
			url: '/_service/availability/get.ashx',			
			data: 'fewoid=' + fewoID + '&date=' + this.selectedDate.format('dd.MM.yyyy'),
			secure: false, // because of new Date() in JSON security-check has to be disabled
			onSuccess: this.renderMonth.bind(this)
		}).send();
	},
	
	renderMonth: function (responseJSON, responseText) {
		var tmpDate = new Date(responseJSON.DateStart);					
		this.items.each(function (item, index) {	
			
			item.removeClass('spacer');
			item.empty();
			if (tmpDate.getMonth() != this.selectedDate.getMonth()) item.addClass('spacer');
			
			var element;
			var label = tmpDate.getDate().lz(2);
			switch (responseJSON.States[index].toInt()) {
				
				case 1: // booked
					element = new Element('span', {'class': 'booked'}).inject(item);
					break;
				case 2: // booked until
					element = new Element('a', {'class': 'booked-until'}).inject(item);
					element.addEvent('click', this.showContextMenu.bindWithEvent(this, ['booked-until', new Date(tmpDate)]));
					break;
				case 3: // booked from
					element = new Element('a', {'class': 'booked-from'}).inject(item);
					element.addEvent('click', this.showContextMenu.bindWithEvent(this, ['booked-from', new Date(tmpDate)]));
					break;
				case 4: // changeday
					element = new Element('a', {'class': 'changeday'}).inject(item);
					element.addEvent('click', this.showContextMenu.bindWithEvent(this, ['changeday', new Date(tmpDate)]));
					break;
				case 5: // available
					element = new Element('span', {'class': 'available'}).inject(item);
					break;
				
				case 12: // selected-from
					element = new Element('span', {'class': 'selected-from'}).inject(item);
					break;
				case 13: // selected-until
					element = new Element('span', {'class': 'selected-until'}).inject(item);
					break;
				case 14: // selected
					element = new Element('a', {'class': 'selected'}).inject(item);
					element.addEvent('click', this.showContextMenu.bindWithEvent(this, ['selected', new Date(tmpDate)]));
					break;
				case 15: // selected
					element = new Element('span', {'class': 'selected'}).inject(item);
					break;
				
			}
			element.set('text', label);
			tmpDate.setDate(tmpDate.getDate() + 1);
			
		}, this);
	},
	
	buildContextMenu: function () {
		this.contextMenu = new Element('ul', {id: 'availability-contextmenu'});
		this.contextMenu.addEvent('mouseleave', this.hideContextMenu.bind(this));
		this.contextMenuOptions = {
			arrival: new Element('li').adopt(new Element('a', {'href': '#', 'text': FEWO.Dict.get('LINK-DETAILS-DATEMENU-ARRIVAL')})).inject(this.contextMenu),
			departure: new Element('li').adopt(new Element('a', {'href': '#', 'text': FEWO.Dict.get('LINK-DETAILS-DATEMENU-DEPARTURE')})).inject(this.contextMenu)
		};
		this.contextMenu.inject(document.body);
	},
	
	showContextMenu: function (event, type, date) {
		var arrival = this.contextMenuOptions.arrival.getElement('a');
		arrival.removeEvents('click');
		arrival.addEvent('click', this.setAvailability.bindWithEvent(this, [1, date.format('dd.MM.yyyy')]));
				
		var departure = this.contextMenuOptions.departure.getElement('a');
		departure.removeEvents('click');
		departure.addEvent('click', this.setAvailability.bindWithEvent(this, [2, date.format('dd.MM.yyyy')]));
		
		this.contextMenuOptions.arrival.setStyle('display', (type == 'booked-from') ? 'none' : 'block');
		this.contextMenuOptions.departure.setStyle('display', (type == 'booked-until') ? 'none' : 'block');
		
		this.contextMenu.setStyles({
			'left': event.page.x - 6,
			'top': event.page.y - 6,
			'display': 'block'
		});
	},
	
	hideContextMenu: function () {
		this.contextMenu.setStyle('display', 'none');
	},
	
	setAvailability: function (event, op, date) {
		event.stop();
		this.hideContextMenu();
		new Request.JSON({
			url: '/_service/availability/set.ashx',
			data: 'fewoid=' + fewoID + '&date=' + date + '&op=' + op,
			secure: false, // because of new Date() in JSON security-check has to be disabled
			onSuccess: this.updateInfos.bind(this)
		}).send();
	},
	
	setInitalAvailability: function (date) {
		this.selectedDate = date;
		new Request.JSON({
			url: '/_service/availability/set.ashx',
			data: 'fewoid=' + fewoID,
			secure: false, // because of new Date() in JSON security-check has to be disabled
			onSuccess: this.updateInfos.bind(this)
		}).send();
	},
	
	updateInfos: function (responseJSON, responseText) {
		
		// refresh calendar view
		this.getAvailability(this.selectedDate);
		
		// display dates (100 is the fullyear of an initialdate in .NET)
		$('availability-datefrom').set('text', (responseJSON.DateFrom.getFullYear() != '100') ? responseJSON.DateFrom.format('dd.MM.yyyy') : '-');
		$('availability-dateuntil').set('text', (responseJSON.DateUntil.getFullYear() != '100' && responseJSON.Result != 1) ? responseJSON.DateUntil.format('dd.MM.yyyy') : '-');
		
		// clear bookingurl
		this.bookingurl = null;
		
		// display price
		if ([3, 4].contains(responseJSON.Result)) {
			var priceinfo = FEWO.Dict.get('TEXT-AVAILABILITY-PRICEINFO');
			priceinfo = priceinfo.replace('#NUM#', responseJSON.NumOfDays);
			priceinfo = priceinfo.replace('#CURRENCY#', '<span>' + responseJSON.Currency);
			priceinfo = priceinfo.replace('#PRICE#', responseJSON.Price + '.&ndash;</span>');
			$('availability-priceinfo').set('html', priceinfo);
			
			// write bookingurl
			if (bookingurl) {
				this.bookingurl = bookingurl;
				this.bookingurl = this.bookingurl.replace('#ARRIVALDAY#', responseJSON.DateFrom.format('dd'));
				this.bookingurl = this.bookingurl.replace('#ARRIVALMONTH#', responseJSON.DateFrom.format('MM'));
				this.bookingurl = this.bookingurl.replace('#ARRIVALYEAR#', responseJSON.DateFrom.format('yyyy'));
				this.bookingurl = this.bookingurl.replace('#DEPARTUREDAY#', responseJSON.DateUntil.format('dd'));
				this.bookingurl = this.bookingurl.replace('#DEPARTUREMONTH#', responseJSON.DateUntil.format('MM'));
				this.bookingurl = this.bookingurl.replace('#DEPARTUREYEAR#', responseJSON.DateUntil.format('yyyy'));
				// Begasoft-Fix
				this.bookingurl = this.bookingurl.replace('#DEPARTURDAY#', responseJSON.DateUntil.format('dd'));
				this.bookingurl = this.bookingurl.replace('#DEPARTURMONTH#', responseJSON.DateUntil.format('MM'));
				this.bookingurl = this.bookingurl.replace('#DEPARTURYEAR#', responseJSON.DateUntil.format('yyyy'));
				
				this.bookingurl = this.bookingurl.replace('#NIGHTS#', responseJSON.NumOfDays);
				
				// enable book-button
				this.enableButton(this.buttons.book);
				
				// hide contact-button
				this.buttons.contact.getParent().setStyle('visibility', 'hidden');
			
			// show error no bookingurl
			} else {
				$('availability-priceinfo').set('text', FEWO.Dict.get('ERROR-AVAILABILITY-NO-BOOKINGURL'));
			}
		
		// no price-information
		} else if (responseJSON.Result == 2) {
			$('availability-priceinfo').set('text', FEWO.Dict.get('ERROR-AVAILABILITY-NOPRICE'));
			this.disableButton(this.buttons.book);
			this.buttons.contact.getParent().setStyle('visibility', 'visible');
		
		// invalid timespan
		} else {
			$('availability-priceinfo').set('text', FEWO.Dict.get('ERROR-AVAILABILITY-INVALIDTIMESPAN'));
			this.disableButton(this.buttons.book);
			this.buttons.contact.getParent().setStyle('visibility', 'visible');
		}
		
	},
	
	disableButton: function (button) {
		button.set('disabled', true);
		button.addClass('disabled');
	},
	
	enableButton: function (button) {
		button.set('disabled', false);
		button.removeClass('disabled');
	},
	
	sendBookingRequest: function () {
		if (!this.bookingurl) return false;
		// logging
		new Request({
			url: '/_service/log/bookinglink.ashx',
			data: 'fewoid=' + fewoID,
			onSuccess: this.redirectBookingRequest.bind(this)
		}).send();
	},
	
	redirectBookingRequest: function () {
		// google-analytics conversion tracking
		switch (partnerid) {
			case 3: // REKA
				pageTracker._trackPageview('/buchung/click_reka.htm');
				break;
			case 5: // Interhome
				pageTracker._trackPageview('/buchung/click_interhome.htm');
				break;
			case 6: // e-Domizil
				pageTracker._trackPageview('/buchung/click_edomizil.htm');
				break;
			default:
				pageTracker._trackPageview('/buchung/click.htm');
				break;
		}
		
		// show redirect-message
		var msg = new Element('div', {
			'html': FEWO.Dict.get('TEXT-BOOKINGREDIRECT-INFO').replace('#PARTNER#', partnername),
			'styles': {
				'text-align': 'center'
			}
		});
		SqueezeBox.initialize({
	        size: {x: 400, y: 50},
	        handler: 'adopt'
	    });
		SqueezeBox.fromElement(msg);
		
		// redirect
		window.location.href = this.bookingurl;
		
		// new window
		//window.open(this.bookingurl, '_blank');
	}
		
};