﻿var currentRoom;
var map;
var vacancies = [];

function loadRoom(objectID, roomID)
{
	$.ajax({
		type: 'GET',
		url: 'php/room.php?object_id=' + objectID + '&room_id=' + roomID,
		dataType: 'json',
		success: showRoom,
		error: function() { alert('Abfrage der Wohnungsdaten fehlgeschlagen!'); }
	});
}

function updateFavoritesList()
{
	$.ajax({
		type: 'GET',
		url: 'php/favorites.php',
		dataType: 'json',
		success: function(json, textStatus)
		{	
			if (json.favorites.length === 0) {
				$('#num_favorites').text('leer');
				$('#favorites').html('Keine Objekte in der Merkliste');
				return;
			}

			$('#num_favorites').text(json.favorites.length);

			var html = '';
			for (var i = 0; i < json.favorites.length; i++) {
				var f = json.favorites[i];
				html += '<div><a href="javascript: loadRoom(' + f.ObjectID + ',' + f.RoomID + ');">';
				html += f.Location + ', ' + f.Street + ' (' + f.Description + ')';
				html += '</a></div>';
			}
			$('#favorites').html(html);
		},
		error: function() { alert('Abfrage der Merkliste fehlgeschlagen!'); }
	});
}

function updateFavorite(isFavorite)
{	
	if (!isFavorite) {
		$("#fav_holder").removeClass("selected")
		$("#fav_link").attr('title','zur Merkliste hinzufügen');
	} else {
		$("#fav_holder").addClass("selected")
		$("#fav_link").attr('title','aus Merkliste entfernen');
	}
}

function toggleFavorite()
{
	$.post(
		'php/favorites.php',
		{
			action: currentRoom.IsFavorite ? 'del' : 'add',
			object_id: currentRoom.ObjectID,
			room_id: currentRoom.RoomID
		},
		function() {
			currentRoom.IsFavorite = !currentRoom.IsFavorite;
			updateFavorite(currentRoom.IsFavorite);
			
			updateFavoritesList();
		}
	);
	return false;
}

function showRoom(json, textStatus)
{
	
	$('#objectHeader').html(json.Description + ', ' + json.Street);
	updateFavorite(json.IsFavorite);
	$('#squareMeter').html(json.Size);
	var x = -60 * (json.Rooms);
	$('#infoIconRooms').css({backgroundPosition:x+'px 0px'});
	// alert(json.Persons);
	x = -60 * (json.Persons-2);
	$('#infoIconPersons').css({backgroundPosition:x+'px 0px'});
	x = -60 * json.Pets;
	$('#infoIconAnimals').css({backgroundPosition:x+'px 0px'});

	if (json.Sauna) {
		$('#infoIconSauna').show();
	} else {
		$('#infoIconSauna').hide();
	}
	if (json.Fireplace) {
		$('#infoIconFireplace').show();
	} else {
		$('#infoIconFireplace').hide();
	}
	if (json.Bikes) {
		$('#infoIconBikes').show();
	} else {
		$('#infoIconBikes').hide();
	}

	$('#object_description').html('<p>' + json.ObjectNotes + '</p>');
	$('#situation').html('<p>' + json.Situation + '</p>');
	$('#room_description').html('<p>' + json.RoomNotes + '</p>');
	$("#room_images").html("");
	for (i = 0; i < json.RoomImages.length; i++) {
		$("#room_images").append('<img title="Klicken f&uuml;r vergr&ouml;&szlig;erte Ansicht" class="room_img" id="room_img_' + i + '" src="' + json.RoomImages[i] + '" width="272">&nbsp;');
		$("#room_img_" + i).click(onImgClicked);
	}

	vacancies = [];
	for (i = 0; i < json.RoomVacancies.length; i++) {
		addVacancy(json.RoomVacancies[i].Start, json.RoomVacancies[i].End);
	}
	$("#vacanciesCal").datepicker("change", {});

	$('#min_price').text(json.MinPrice);
	$('#max_price').text(json.MaxPrice);

	var prices_html = "<table id=\"price_table\"><tr><th>Von</th><th>Bis</th><th>Preis</th></tr>";
	for (i = 0; i < json.Seasons.length; i++) {
		prices_html += "<tr class=" + (i % 2 ? "odd" : "even") + ">";
		//prices_html += "<td>" + json.Seasons[i].Season + "</td>";
		prices_html += "<td>" + json.Seasons[i].Start + "</td>";
		prices_html += "<td>" + json.Seasons[i].End + "</td>";
		prices_html += "<td align=\"center\">&euro;" + json.Seasons[i].Price + "</td>";
		prices_html += "</tr>";
	}
	$("#room_prices").html(prices_html + "</table>");

	currentRoom = json;
	$('#startUsedom').hide();
	$('#houseGeneral').hide();
	
	$('#objectDetails').show();

	$('#route_link').attr('href', 'http://maps.google.com/maps?daddr=' + currentRoom.Street + ', ' + currentRoom.Location + '@' + currentRoom.Latitude + ',' + currentRoom.Longitude);

	$("#room_map").html("");
	if ($('#p7tpb1_5').is('.down')) {
		loadMap();
	} else if ($('#p7tpb1_6').is('.down')) {
		loadBookingMask();
	}
}

function loadMap()
{
	if (!currentRoom) {
		return;
	}

	if (!GBrowserIsCompatible()) {
		$("#room_map").html("Ihr Browser unterst&uuml;tzt Google Maps leider nicht!");
		return;
	}
	lon_fields = currentRoom.Longitude.split(" ");
	lat_fields = currentRoom.Latitude.split(" ");
	longitude = parseFloat(lon_fields[0]) + (parseFloat(lon_fields[1]) / 60) + (parseFloat(lon_fields[2]) / 3600);
	latitude = parseFloat(lat_fields[0]) + (parseFloat(lat_fields[1]) / 60) + (parseFloat(lat_fields[2]) / 3600);
	map = new GMap2($("#room_map").get(0));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(latitude, longitude), 15, G_NORMAL_MAP);
	marker = new GMarker(map.getCenter());
	map.addOverlay(marker);
}

function loadBookingMask(){
	if (!currentRoom) {
		return;
	}
	$('#booking').attr('src', 'https://zimmer.im-web.de/Buchung.php3?id=8291&objekt_id='+currentRoom.ObjectID);
}

function highlightDays(date)
{
	if (isVacancy(date)) {
		return [0, 'freeDate'];
	}

	return [0, 'occupiedDate'];
}

function isVacancy(date)
{
	date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
	for (var i = 0; i < vacancies.length; i++) {
		if (date >= vacancies[i].start && date <= vacancies[i].end) {
			return true;
		}
	}

	return false;
}

function addVacancy(start, end)
{
	startFields = start.split('-');
	endFields = end.split('-');

	var startDate = new Date(parseInt(startFields[0], 10), parseInt(startFields[1], 10) - 1, parseInt(startFields[2], 10), 0, 0, 0, 0);
	var endDate = new Date(parseInt(endFields[0], 10), parseInt(endFields[1], 10) - 1, parseInt(endFields[2], 10), 0, 0, 0, 0);

	vacancies.push({'start': startDate, 'end': endDate});
}

function showHouse(houseID)
{
	$('#startUsedom').hide();
	$('#objectDetails').hide();

	$.ajax({
		type: 'GET',
		url: 'php/get_house.php',
		data: { house_id: houseID },
		dataType: 'json',
		success: function (json) {
			//description = json.Description.replace(/\n/g, '<br />');
			$('#house_name').val(json.Name);
			$('#houseDescr').html('<p><b>' + json.Name + '</b></p><p>' + json.Description + '</p>');
			$('#imgHolder').html('');

			for (var i = 1; i <= 3; i++) {
				if (json['Image' + i] != '') {
					$('#imgHolder').append('<p><img class="houseImg" src="/ferienwohnungen/images/' + json['Image' + i] + '" /></p>');
				}
			}
			//$('#houseImg').attr('src', '/ferienwohnungen/images/' + json.Image1);
			$('#houseGeneral').show();
		},
		failure: function() { alert('Laden der Hausdaten fehlgeschlagen!'); }
	});
}

function init()
{
	// Vacancy calendar
	$('#objectDetails').hide();
	$('#objectGeneral').hide();
	P7_initPM(1,0,1,-20,10);
	P7_initTP(8,29);
	$("#vacanciesCal").datepicker({
		beforeShowDay: highlightDays,
		numberOfMonths: 3,
		minDate: 0,
		maxDate: 545,
		firstDay: 1,
		changeFirstDay: false
	}).children('div').css('width', '555px');
	$.datepicker.setDefaults($.datepicker.regional['de']);
	$("#start_date, #end_date").datepicker({
			showOn: "both",
			minDate: 0,
			maxDate: 545,
			firstDay: 1,
			changeFirstDay: false,
			numberOfMonths: 3,
			buttonImage: "images/cal.gif",
			buttonImageOnly: false
		});
		//.attr("readonly", "readonly");
	
	// Map
	$("#p7tpb1_5").click(loadMap); 
	$("#p7tpb1_6").click(loadBookingMask);
	
	// Favorites
	$('#fav_holder').click(toggleFavorite);
	updateFavoritesList();
	initTree();
	$('#update_tree').click(initTree);
}

function initTree()
{
	P7_ABclose('1_2');

	query_string = new Querystring();
	var objectID = query_string.get('object_id');
	var roomID = query_string.get('room_id');


	$('#tree').html('');
	$("#tree").dynatree({
		title: 'Ferienorte',
		rootVisible: true,
		focusRoot: true,
		rootCollapsible: false,
		imagePath: 'css/treeskin/',
		icon: 'root.gif',
		strings: {
			loading: 'Lade Unterkünfte...',
			loadError: 'Ladefehler!'
		},
		initAjax: {
			url: 'php/tree_locations.php',
			data: $('#filter_form').serialize(),
			complete: function() {
				var root = $("#tree").dynatree("getRoot");

				if (objectID && roomID) {
					var n = root.visit(function(dtnode, data) {
						if (dtnode.data.key.oid == objectID && dtnode.data.key.rid == roomID) {
							dtnode.select();
						}
					}, false, true);
				}
			}
		},
		onFocus: function(dtnode) {
			if (dtnode.data.key != 'root') {
				return;
			}
			$('#houseGeneral').hide();
			$('#objectDetails').hide();
			$('#startHead').text('unseren Ferienorten');	
			$('#mapPic').attr({src:'images/usedom.jpg', title: 'unsere Ferienorte auf der Insel Usedom'});
			$('#startUsedom').show();
		},
		onSelect: function(dtnode) {
			switch(dtnode.data.key.type) {
			case 'location': 
				$('#houseGeneral').hide();
				$('#objectDetails').hide();
				$('#startHead').text(dtnode.data.title);
				$('#mapPic').attr({
					src: 'images/' + dtnode.data.key.image,
					title: 'Überblick für ' + dtnode.data.title
				});
				$('#startUsedom').show();
				break;
			case 'house':
				showHouse(dtnode.data.key.id);
				break;
			case 'object':
				loadRoom(dtnode.data.key.oid, dtnode.data.key.rid);
				break;
			case 'no_results':
				if (confirm('Weitere Angebote auf unserer Partnerwebseite suchen?')) {
					window.location = 'http://www.gastgeber2009.de/';
				}
				break;
			default:
			}
		}
	});
}

$(init);


/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

