// Helper class

function RecordCollection(arrayOfObjects) {
	
	this.collection = arrayOfObjects;
	
	this.getRecordById = function(id) {
		for (var rec in this.collection) {
			if (this.collection[rec].id == id) return this.collection[rec];
		}
		return null;
	}
}

Date.prototype.getJSDate = function(phpDate) {
	/*
	var day = phpDate.substring(0,2);
	var mon = phpDate.substring(3,5);
	var yr = phpDate.substring(6,10);
	*/
	var yr = phpDate.substring(0,4);
	var mon = phpDate.substring(5,7);
	var day = phpDate.substring(8,10);
	var jsDate = new Date();
	jsDate.setDate(day);
	jsDate.setMonth(mon-1);
	jsDate.setFullYear(yr);
	return jsDate;
};
	
Date.prototype.getPhpDate = function(jsDate) {
	var phpDate = "";
	var day = jsDate.getDate();
	var month = jsDate.getMonth()+1;
	var year = jsDate.getFullYear();
	if (month<10) month = "0" + month;
	if (day<10) day = "0" + day;
	//phpDate = day + "-" + month + "-" + year;
   	phpDate = year + "-" + month + "-" + day ;
	return phpDate;
};

// Room selector

function RoomSelector(containerId, roomTypes) {
	
	// TEST DATA - MUST BE PASSED DURING OBJECT CREATION
	this.maxRooms = 7;
	this.roomTypes = roomTypes;
	this.containerId = containerId;
	this.stay = new Stay();
	
	this.roomTypeCollection = new RecordCollection(this.roomTypes);
	
	document.roomSelector = this;
	
	this.addEventListener = function(el, e, f) {
		if (el.attachEvent) { // IE
			el.attachEvent("on" + e, f);
		} else if (el.addEventListener) { // Gecko / W3C
			el.addEventListener(e, f, false);
		} else {
			el["on" + e] = f;
		}
	} 
	
	this.init = function() {
		// create add room button
		elInput = document.createElement("input");
		elInput.setAttribute("type", "button");
		//elInput.setAttribute("value", "Ýlave oda ekle +");
		elInput.setAttribute("value", OLang.L["ADDBUTTON"]);
		elInput.setAttribute("onclick", "document.roomSelector.addNewRoom();");
		document.getElementById(this.containerId).appendChild(elInput);
		elInput.className = "add-room-button";
		elInput.parentNode.innerHTML = elInput.parentNode.innerHTML;
		// add a room by default
		this.addNewRoom();
	}

	this.addNewRoom = function(){
		
		// creates a new room selection line
		// with a select box with room type names and ids
		// an adults select box from 1 to maxAdults per active room type
		// a children select box from 1 to maxAdults per active room type
		
		// max 7 rooms may be selected
		rc = this.stay.getRoomCount();
		if (rc >= this.maxRooms) return;
		
		// first update model: JSStay object
		this.stay.addRoom();
		rc= this.stay.getRoomCount();
		
		roomtypes = this.roomTypes;
		roomTypesCount = roomtypes.length;
		
		// create new line
		var newDiv = document.createElement("div");
		newDiv.className = "room-line";
		//var divText = document.createTextNode("Oda " + rc + ":");
		var divText = document.createTextNode(OLang.L["ROOM"] + " " +rc + ":");
		newDiv.appendChild(divText);
		
		// create room type select
		var roomTypeSelect = document.createElement("select");
		roomTypeSelect.setAttribute("id", "room-type-"+rc);
		roomTypeSelect.name = "room-type-"+rc;
		
		for (i=0; i<roomTypesCount; i++) {
			var option = document.createElement("option");
			option.setAttribute("value", roomtypes[i].id);
			var optionText = document.createTextNode(roomtypes[i].name);
			option.appendChild(optionText);
			roomTypeSelect.appendChild(option);
		}
		// create guests text
		//var guestsText = document.createTextNode("Misafir:");
		var guestsText = document.createTextNode(OLang.L["GUEST"]+":");
		
		// create guests select
		var guestsSelect = document.createElement("select");
		guestsSelect.setAttribute("id", "guests-"+rc);
		guestsSelect.setAttribute("name", "guests-"+rc);
		maxGuests = roomtypes[0].maxGuests+1;
		for (i=1; i<maxGuests; i++) {
			var option = document.createElement("option");
			option.setAttribute("value", i);
			if (i==2) option.setAttribute("selected", "selected");
			var optionText = document.createTextNode(i);
			option.appendChild(optionText);
			guestsSelect.appendChild(option);
		}
		
		// create description area
		var defaultDescriptionText = roomtypes[0].description;
		descriptionSpan = document.createElement("div");
		descriptionSpan.setAttribute("id", "rd-"+rc);
		descriptionSpan.className = "room-description";
		var description = document.createTextNode(defaultDescriptionText);
		descriptionSpan.appendChild(description);
		
		// create delete button if room number is more than 1
		deleteButton = null;
		if (rc>1) {
			deleteButton = document.createElement("input");
			deleteButton.setAttribute("type", "button");
			deleteButton.setAttribute("id", "delete-"+rc);
			//deleteButton.setAttribute("value", "Odayý sil");
			deleteButton.setAttribute("value", OLang.L["REMOVEROOM"]);
		} 
		
		newDiv.appendChild(roomTypeSelect);
		newDiv.appendChild(guestsText);
		newDiv.appendChild(guestsSelect);
		if (rc>1) {
			newDiv.appendChild(deleteButton);
		}
		
		newDiv.appendChild(descriptionSpan);
		addButton = document.getElementById(this.containerId).lastChild;
		document.getElementById(this.containerId).insertBefore(newDiv, addButton);
		
		// Assign event handlers
		// 1st room type select
		var onchangeFunction = "document.roomSelector.handleRoomTypeChange("+rc+");"
		function onchange(){
			eval(onchangeFunction);
		}
		var el = document.getElementById(roomTypeSelect.id);
		this.addEventListener(el, "change", onchange);
		// 2nd delete button
		if (deleteButton!=null) {
			var onclickFunction = "document.roomSelector.deleteRoom("+rc+");";
			function onclickDeleteButton(){
				eval(onclickFunction);
			}
			var el = document.getElementById(deleteButton.id);
			this.addEventListener(el, "click", onclickDeleteButton);
		}
	}
	
	this.handleRoomTypeChange = function(rc) {
		// find out which room type is selected
		var id = "room-type-"+rc;
		var roomTypeId = document.getElementById(id).value;
		// get the maxGuests associated with that room type
		var maxGuestsAllowed = this.roomTypeCollection.getRecordById(roomTypeId).maxGuests;
		// re-build the select
		
		guestsSelectId = "guests-"+rc;
		
		guestsSelect = document.getElementById(guestsSelectId);
		
		// update guests select
		// first remove all options...
		for (o in guestsSelect.options) {
			guestsSelect.remove(o);
		}
		
		// ...then re-build guests select
		maxGuests = maxGuestsAllowed+1;
		
		for (i=1; i<maxGuests; i++) {
			var option = document.createElement("option");
			option.setAttribute("value", i);
			if (i==2) option.setAttribute("selected", "selected");
			var optionText = document.createTextNode(i);
			option.appendChild(optionText);
			guestsSelect.appendChild(option);
		}
		
		// update room description
		var description = this.roomTypeCollection.getRecordById(roomTypeId).description;
		descriptionId = "rd-"+rc;
		document.getElementById(descriptionId).innerHTML = description;
	}
	
	this.deleteRoom= function(roomId){
		//alert(roomId);
		// do not let deleting the first room
		if (roomId<2) return;
		var roomsCount = this.stay.getRoomCount();
		// a non-existing room cannot be deleted
		if (roomId>roomsCount) return;
		
		// copies info about each room into an array
		// removes the to-be-deleted room item from array
		var rooms = new Array();
		var newIndex = 0; 
		for (var i=1; i<=roomsCount; i++) {
			if (i!=roomId) {// do not include info about the to-be-deleted room
				newIndex++;
				roomTypeId = "room-type-"+i;
				roomTypeSelect = document.getElementById(roomTypeId);
				roomTypeIndex = roomTypeSelect.selectedIndex;
				
				guestsId = "guests-"+i;
				guestsSelect = document.getElementById(guestsId);
				guestsIndex = guestsSelect.selectedIndex;
				
				roomInfo = new Array();
				roomInfo["id"] = newIndex;
				roomInfo["roomTypeIndex"] = roomTypeIndex;
				roomInfo["guestsIndex"] = guestsIndex;
				
				rooms[newIndex] = roomInfo;
			}
		}
		// now we have one less room
		rooms["count"]=newIndex;
		
		// removes all rooms from document
		document.getElementById(this.containerId).innerHTML = "";
		
		// re-creates rooms using the array
		// TEST
		this.stay.clear();
		var count =rooms["count"];
		
		for (var i=1; i<=count; i++) {
			if (i==1) {
				this.init();// create button, too
			} else this.addNewRoom();
			
			var roomInfo = rooms[i];
			var roomTypeId = "room-type-"+i;
			
			var roomTypeSelect = document.getElementById(roomTypeId);
			roomTypeSelect.selectedIndex = roomInfo["roomTypeIndex"];
			this.handleRoomTypeChange(i);
			
			var guestsId = "guests-"+i;
			var guestsSelect = document.getElementById(guestsId);
			guestsSelect.selectedIndex = roomInfo["guestsIndex"];
		}
		
	}
	
	this.buildFromRooms = function(rooms) {
		var count = rooms["count"];
		if (count<1) return;//must not be empty
		this.init();//let's create the widget
		var roomInfo = rooms[1];
		document.getElementById("room-type-1").selectedIndex =roomInfo["roomTypeIndex"];
		this.handleRoomTypeChange(1);
		document.getElementById("guests-1").selectedIndex = roomInfo["guestsIndex"];
		
		for (var i=2; i<=count; i++) {
			this.addNewRoom();
			roomInfo = rooms[i];
			roomTypeId = "room-type-"+i;
			guestsId = "guests-"+i;
			document.getElementById(roomTypeId).selectedIndex =roomInfo["roomTypeIndex"];
			this.handleRoomTypeChange(i);
			document.getElementById(guestsId).selectedIndex = roomInfo["guestsIndex"];
		}
		
	}
	
	this.updateRoom= function(roomId, roomType, adults, children){}
	
	this.getStay = function() {return this.stay;}
}

function RoomType(){
	this.id = 0;
	this.name = "Default room";
	this.maxGuests = 2;
	this.maxAdults = 2;
	this.description = "A room type with 2 max guests.";
}

function Room() {
	this.id = 0;
	this.roomType = 0;
	this.guests = 0;
}

function Stay() {
	this.roomCount = 0;
	this.addRoom = function() { this.roomCount++; }
	this.getRoomCount = function() {return this.roomCount;}
	this.clear = function() {this.roomCount = 0;}
}

function init() {
	document.stay = new Stay();
	//alert(document.stay.roomCount);
}

function checkAvailability() {
	var stay = document.roomSelector.getStay();
	rc = stay.getRoomCount();
	document.getElementById("room-count").value=rc;
	rsForm = document.getElementById("room-selection-form");
	rsForm.submit();
}

function updateForm(state) {
	switch (state) {
		case "creditCard":
			//alert("creditCard");
			document.getElementById("credit-card-info").innerHTML= ccInfoHTML;
			//document.getElementById("payment-amount-info").innerHTML= paymentAmountHTML;
			document.getElementById("credit-card-info").style.height = "auto";
			document.getElementById("payment-amount-info").innerHTML="";
			document.getElementById("payment-amount-info").style.height = 0;
			fc.init();
			break;
		case "bankTransfer":
			//alert("bankTransfer");
			document.getElementById("credit-card-info").innerHTML="";
			document.getElementById("credit-card-info").style.height = 0;
			document.getElementById("payment-amount-info").innerHTML= paymentAmountHTML;
			document.getElementById("payment-amount-info").style.height = "auto";
			fc.init();
			break;
		case "payAtHotel":
			document.getElementById("credit-card-info").innerHTML="";
			document.getElementById("payment-amount-info").innerHTML="";
			document.getElementById("credit-card-info").style.height = 0;
			document.getElementById("payment-amount-info").style.height = 0;
			fc.init();
			break;
	}
}

function isEarlier(date1, date2) {
	d1 = new Date();
	d2 = new Date();
	d1 = date1;
	d2 = date2;
	if ( d1.getFullYear() < d2.getFullYear() ) return true;
	if ( d1.getFullYear() > d2.getFullYear() ) return false;
	if ( d1.getFullYear() == d2.getFullYear() ) {
		if ( d1.getMonth() < d2.getMonth() ) return true;
		if ( d1.getMonth() > d2.getMonth() ) return false;
		if ( d1.getMonth() == d2.getMonth() ) {
			if ( d1.getDate() < d2.getDate() ) {
				return true;
			} else return false;
		}
	}
}

function cancelBooking(bookingId) {
	if (confirm("Rezervasyonu iptal etmek istediï¿½inize emin misiniz?")){
		document.getElementById("bid").value = bookingId;
		document.getElementById("com").value = "cancel booking";
		document.getElementById("form").action = "manage_bookings.php";
		document.getElementById("form").submit();
	}
}

function makeBookingDefinitive(bookingId) {
	if (confirm("Rezervasyonu kesinleï¿½tirmek istediï¿½inize emin misiniz?")){
		document.getElementById("bid").value = bookingId;
		document.getElementById("com").value = "make definitive";
		document.getElementById("form").submit();
	}
}

function showBookingDetails(bookingId) {
	document.getElementById("com").value = "show booking";
	document.getElementById("bid").value = bookingId;
	document.getElementById("form").action = "showBookingDetails.php";
	document.getElementById("form").submit();
	
}

function writeDate(phpDate){
	var jsDate = new Date().getJSDate(phpDate);
	document.write(jsDate.print("%d %B %Y, %A"));
}

function shiftView(type) {
	var currentDate = document.getElementById("startDate").value;
	var yr = currentDate.substring(0,4);
	var mon = currentDate.substring(5,7);
	var day = currentDate.substring(8,10);
	var jsDate = new Date();
	
	jsDate.setDate(day);
	jsDate.setMonth(mon);
	jsDate.setFullYear(yr);
	switch(type){
		case "fw":
			jsDate.setDate(jsDate.getDate()+5);
			break;
		case "bw":
			jsDate.setDate(jsDate.getDate()-5);
			break;
		case "fd":
			jsDate.setDate(jsDate.getDate()+1);
			break;
		case "bd":
		jsDate.setDate(jsDate.getDate()-1);
			break;
		case "n":
		break;
		default:
			return;
			break;	
	}
	document.getElementById("hotel-status").innerHTML="";
	if (type=="n") {
		document.getElementById("showStatusForm").submit();
		return;
	}
	var phpDay = jsDate.getDate();
	var phpMonth = jsDate.getMonth();
	var phpYear = jsDate.getFullYear();
	if (phpMonth<10) phpMonth = "0" + phpMonth;
	if (phpDay<10) phpDay = "0" + phpDay;
	//startDate = phpDay + "-" + phpMonth + "-" + phpYear;
	startDate = phpYear + "-" + phpMonth + "-" + phpDay;
	document.getElementById("startDate").value = startDate;
	document.getElementById("showStatusForm").submit();
}

function updateNightsCount(lang) {
	var checkin = document.getElementById("hiddenCheckin");
	var checkout = document.getElementById("hiddenCheckout");
	if (document.checkout) {
		//alert(document.checkin);
		//alert(document.checkout);
		document.checkin.setHours(0,0,0,0);
		document.checkout.setHours(0,0,0,0);
		var diff = (document.checkout.getTime() - document.checkin.getTime())/(60*60*24*1000);
		diff = Math.floor(diff);
		//alert(document.checkout.getTime() - document.checkin.getTime());
		//var diff = checkout-checkin;
		if(lang=="tr") document.getElementById("night-count").innerHTML = diff + " gece";
		else document.getElementById("night-count").innerHTML = diff + " nights";
	}
}