/* ws/fastSearch/static/js/property.js */ /* UTF8-Côôkie */

/*
Cookies:

VISITED_PROPERTIES
REQUESTED_PROPERTIES

*/


function	propertyClass(id, name, calendarType, calendarUrl, backToSearchText, addToRequestListText, removeFromRequestListText, makeRequestText, viewRequestListText)
{
	var	self = this;

	// Config

	this.dateFormat = '%a, %d %b %Y';
	this.missingText = 'Please fill-in the fields marked as missing and try again.';
	this.invalidText = 'Please fill-in the fields marked as invalid and try again.';
	this.emailConfirmFailureText = 'The confirmed email address does not match the original.';
	this.errorText = 'An unexpected error occured. Please try again later.';
	this.requestSubmittedText = 'Your requested was submitted.\nThank you.';

	this.addToRequestListText = addToRequestListText;
	this.removeFromRequestListText = removeFromRequestListText;

	// 21/12/2009
	this.makeRequestText = makeRequestText;
	this.viewRequestListText = viewRequestListText;


	this.calendarForwardButtonText  = 'Next';
	this.calendarBackButtonText 	= 'Back';
	this.calendarMonthsToDisplay = 6;



	// Init

	this.propertyId = id;
	this.propertyName = name;
	this.calendarType = calendarType;
	this.calendarUrl = calendarUrl;
	this.backToResultListText = backToSearchText;

	this.currentCalendar = null;
	this.calendarStartDate = null;
	this.calendarAndControlsContainer = null;
	this.calendarContainer = null;
	this.calendarPrevButton = null;
	this.calendarNextButton = null;

	this.requestedCookie = kigoCookie.get('REQUESTED_PROPERTIES', '');
	this.requestedList = kigoList.createFromCSV(this.requestedCookie, ':');

	vkDom.onLoad(
		function()
		{
			self.init();
		}
	);
}


propertyClass.prototype.init = function()
{
	var	self = this;

	// 19/11/2009
	// Setup "Add to request list" / "Remove from request list" toggle - depends on cookie
	// This is the first thing to be done...

	this.renderRequestListToggle(this.requestedList.find(this.propertyId));

	// Okay, setup the periodic in-request-list check, so that if the property is moved into the list in another
	// page, the change is reflected here
	setInterval(
		function()
		{
			var	newCookie = kigoCookie.get('REQUESTED_PROPERTIES', '');

			if(newCookie != self.requestedCookie)
			{
				self.requestedCookie = newCookie;
				self.requestedList = kigoList.createFromCSV(newCookie, ':');

				// Render
				self.renderRequestListToggle(self.requestedList.find(self.propertyId));
			}
		},
		2500
	);


	// Add the "back" link if coming from the search page...
	if(
		kigoCookie.get('LAST_SEARCH') !== null &&
		this.backToResultListText.length	
	)
	{
		(new kigoDom('searchmenus')).append(
			kigoDom.create('div', { 'className' : 'back_to_list' }).append(
				kigoDom.create('a', {
										'href'	:	WS_ROOT+_SEARCH_URL+'#'+kigoCookie.get('LAST_SEARCH'),
										'title'	:	this.backToResultListText
									}).append(
					kigoDom.create('span').append(
						this.backToResultListText
					)
				)
			)
		);

		// 22/12/2009 - We no longer forget the last search
		// kigoCookie.unset('LAST_SEARCH');
	}

	// 18/11/2009 - Act only if the block does exist in DOM tree
	if(vkDom.el('availability_calendar'))
	{
		if(window.location.hash == '#availability_calendar')
		{
			this.openCalendar();

			// Using timeout seems to work with all browsers (IE6 not tested)
			setTimeout(
				function()
				{
					window.location.hash = '#availability_calendar';
				},
				1
			);
			// Doesn't work in Safari, Chrome & friends
			//window.location.hash = '#availability_calendar';
		}
		else if(vkDom.el('availability_calendar').offsetWidth)
			this.loadCalendar();	// If displayed, load anyway....
	}

	// 02/02/2009 - THIS APPLIES TO PROPERTIES WITHOUT REQUEST FORM TOO!
	// 17/11/2009 - ALL PROPERTIES ARE NOW IMPLICITLY LINKED TO THE REQUEST FORM
	// "Also interested in" feature - remember that this property was visited...

	var	visitedList = kigoList.createFromCSV(kigoCookie.get('VISITED_PROPERTIES', ''), ':');
	if(!visitedList.find(this.propertyId))
	{
		visitedList.add(this.propertyId);
		kigoCookie.set('VISITED_PROPERTIES', visitedList.CSV(':'));
	}
}










/*************************************************************/
/* Calendars-related */



propertyClass.prototype.closeCalendar = function()
{
	// Update menu
	// 18/11/2009 - Noone ever used this - and it doesn't make sense now that request form was removed from here
	// vkDom.removeClass('availability_calendar_menu', 'selected');

	// Update blocks
	//vkDom.addClass('functions_blocks', 'none');
	vkDom.addClass('availability_calendar', 'none');

	return false;
}



propertyClass.prototype.openCalendar = function()
{
	// Update menu
	// 18/11/2009 - Noone ever used this - and it doesn't make sense now that request form was removed from here
	// vkDom.addClass('availability_calendar_menu', 'selected');

	// Update blocks
	//vkDom.removeClass('functions_blocks', 'none');
	vkDom.removeClass('availability_calendar', 'none');

	this.loadCalendar();

	return true;	// #availability_calendar
}

propertyClass.prototype.loadCalendar = function()
{
	if (this.calendarType == CALENDAR_TYPE_KIGO)
		this.reloadKigoCalendar();
	else if(this.calendarType == CALENDAR_TYPE_HAC)
	{
		// Okay, (re)load the calendar

		(new kigoDom('availability_calendar')).getByTagName('div', 0).empty().append(
			kigoDom.create('iframe', {
										// These are required for IE
										'frameBorder'	:	'0',
										'hspace'		:	'0',
										'vspace'		:	'0',
										'marginWidth'	:	'0',
										'marginHeight'	:	'0',
										//'scrolling'		:	'no',
										'src'			:	this.calendarUrl
									}
			)
		);
	}
}



propertyClass.prototype.reloadKigoCalendar = function()
{
	var	self = this;

	// Initialized?
	if(!this.calendarAjax)
	{
		// Ajax instance

		this.calendarAjax = new fsAjaxRequest(true);

		this.calendarAjax.onLoad = function(data)
		{
			if(data != null)
				self.onCalendarAjaxLoad(data);
			else
				this.onError();
		}

		this.calendarAjax.onError = this.calendarAjax.onTimeout = function(data)
		{
			alert(self.errorText);
			self.closeCalendar();
		}

		// Default start date
		this.calendarStartDate = kigoDate.today().firstMonthDay();
	}


	// 18/11/2009 - The loading class is now assigned to #availability_calendar rather than #calendar_container
	vkDom.addClass('availability_calendar', 'loading');

	// Disable the buttons - if they exist (not the first render) ...
	if(this.calendarPrevButton != null)
	{
		vkDom.addClass(this.calendarPrevButton, 'disabled');
		vkDom.addClass(this.calendarNextButton, 'disabled');
	}

	this.calendarAjax.post(
		'ajax/calendar.xml', 			
		{
			'PROP_ID'		:	this.propertyId,
			'START_DATE'	:	this.calendarStartDate.mysql(),
			'END_DATE'		:	this.calendarStartDate.addMonths(this.calendarMonthsToDisplay - 1).lastMonthDay().mysql()
		}
	);
}




propertyClass.prototype.onCalendarAjaxLoad = function(reservations)
{
	var	self = this;
	var	firstRender = false;

	// First render
	if(this.calendarAndControlsContainer == null)
	{
		// This is the very first render - create the kigoCalendar container and controls

		firstRender = true;

		this.calendarAndControlsContainer = vkDom.el('availability_calendar').getElementsByTagName('div')[0];

			this.calendarContainer = document.createElement('div');
			this.calendarContainer.className = 'kigo_calendar';

		this.calendarAndControlsContainer.appendChild(this.calendarContainer);

			var controlsContainer = document.createElement('div');
			controlsContainer.className = 'controls';

			function	createButtonLink(isNext)
			{
				var	a = document.createElement('a');
				a.setAttribute('href', '#');
				a.onclick = function()
				{
					if(!vkDom.hasClass(this, 'disabled'))
					{
						self.calendarStartDate = self.calendarStartDate.addMonths( (isNext ? 1 : -1) * (self.calendarMonthsToDisplay - 1) );
						self.reloadKigoCalendar();
					}
					return false;
				}

				var	span = document.createElement('span');
				span.appendChild(
					document.createTextNode(
						isNext ? self.calendarForwardButtonText : self.calendarBackButtonText
					)
				);

				a.appendChild(span);

				return a;
			}

			function	createButton(isNext, link)
			{
				var	div = document.createElement('div');
				div.className = isNext ? 'forward' : 'back';

				div.appendChild(link);
				return div;
			}

			function	createClear()
			{
				var	div = document.createElement('div');
				div.className = 'clear';
				return div;
			}

			controlsContainer.appendChild(
				createButton(false, this.calendarPrevButton = createButtonLink(false))
			);

			controlsContainer.appendChild(
				createButton(true, this.calendarNextButton = createButtonLink(true))
			);
				
			controlsContainer.appendChild(
				createClear()
			);

		this.calendarAndControlsContainer.appendChild(controlsContainer);
	}


	// Render the calendar itself...
	var	calendar = new kigoCalendar(
		this.calendarStartDate.getMonth(),
		this.calendarStartDate.getYear(),
		this.calendarStartDate.addMonths(this.calendarMonthsToDisplay - 1).getMonth(),
		this.calendarStartDate.addMonths(this.calendarMonthsToDisplay - 1).getYear(),
		{
			'i'		:	null,
			'p'		:	null,
			'f'		:	null,
			'a'		:	null,
			'o'		:	null,
			'l'		:	null,
			'r'		:	reservations
		},
		null,
		null
	);

	this.calendarContainer = calendar.dump(this.calendarContainer);

	// Fix the container size on first render
	if(firstRender)
	{
		// we set the calendar container to the computed height in order to prevent screen flickering on re-rendering

		if(vkDom.hasClass(document.body, 'ua-msie'))
		{
			// Due to the fact that IE does not compute the height for elements that do no have the IE setting hasLayout
			// ie. our div with no css normally attached to it, we have to tricke IE to compute the values we need.
			// placeholder.style.display = 'inline-block'; Will make IE wake up and compute the values we need.
			// http://www.satzansatz.de/cssd/onhavinglayout.html#elem

			var priorSetting = this.calendarAndControlsContainer.style.display;
			this.calendarAndControlsContainer.style.display = 'inline-block';		
			
			this.calendarAndControlsContainer.style.height = this.calendarAndControlsContainer.clientHeight+'px'; 		
			this.calendarAndControlsContainer.style.width = this.calendarAndControlsContainer.clientWidth+'px';
			
			this.calendarAndControlsContainer.style.display = priorSetting;
		}
		else
		{
			this.calendarAndControlsContainer.style.height = this.calendarAndControlsContainer.clientHeight+'px'; 		
			this.calendarAndControlsContainer.style.width = this.calendarAndControlsContainer.clientWidth+'px';
		}
	}


	// Allow or disallow next and previous buttons...
	// Prev button not allowed prior to the current date (server will throw error)
	if(
		this.calendarStartDate.addMonths( -1 * (self.calendarMonthsToDisplay - 1) ).daysDiff(kigoDate.today()) > 60	/* 60 days margin */
	)
		vkDom.addClass(this.calendarPrevButton, 'disabled');
	else
		vkDom.removeClass(this.calendarPrevButton, 'disabled');


	// Five years forward...
	if(
		this.calendarStartDate.addMonths( (self.calendarMonthsToDisplay - 1) ).daysDiff(kigoDate.today()) < -1825
	)
		vkDom.addClass(this.calendarNextButton, 'disabled');
	else
		vkDom.removeClass(this.calendarNextButton, 'disabled');
}















/*************************************************************/
/* Request-list-related (As of 17/11/2009) */


propertyClass.prototype.toggleRequestList = function()
{
	var	pos = this.requestedList.pos(this.propertyId);

	if(pos != null)
		this.requestedList.remove(pos);
	else
		this.requestedList.add(this.propertyId);

	kigoCookie.set('REQUESTED_PROPERTIES', this.requestedCookie = this.requestedList.CSV(':'));

	this.renderRequestListToggle(pos == null);
}

propertyClass.prototype.renderRequestListToggle = function(inList)
{
	/*
	var	link = vkDom.el('request_list_menu').getElementsByTagName('a')[0];

	if(inList)
		vkDom.addClass(link, 'in_list');
	else
		vkDom.removeClass(link, 'in_list');

	function	span(text)
	{
		var	span = document.createElement('span');
		span.appendChild(
			document.createTextNode(text)
		);
		return span;
	}

	vkDom.clean(link);
	link.appendChild(span(inList ? this.removeFromRequestListText : this.addToRequestListText));
	*/

	/////////////////////////////////////////////////////
	// 21/12/2009


	function	span(text)
	{
		var	span = document.createElement('span');
		span.appendChild(
			document.createTextNode(text)
		);
		return span;
	}

	if(vkDom.el('request_list_menu'))
	{
		var	link = vkDom.el('request_list_menu').getElementsByTagName('a')[0];

		if(inList)
			vkDom.addClass(link, 'in_list');
		else
			vkDom.removeClass(link, 'in_list');

		vkDom.clean(link);
		link.appendChild(span(inList ? this.removeFromRequestListText : this.addToRequestListText));
	}

	if(vkDom.el('make_request_menu'))
	{
		var	link = vkDom.el('make_request_menu').getElementsByTagName('a')[0];

		if(inList)
			vkDom.addClass(link, 'in_list');
		else
			vkDom.removeClass(link, 'in_list');

		vkDom.clean(link);
		link.appendChild(span(inList ? this.viewRequestListText : this.makeRequestText));
	}
}



propertyClass.prototype.makeRequest = function()
{
	if(!this.requestedList.find(this.propertyId))
	{
		this.requestedList.add(this.propertyId);
		kigoCookie.set('REQUESTED_PROPERTIES', this.requestedList.CSV(':'));
	}

	return true;	// Default behaviour: go to requests page
}

