var jtk = new JoookToolkit(); // Just to make sure we have JTK


/* 
	JSON example:
	[
		{
			type: 1,
			categoryId: "class1.id",
			categoryName: "class1.name",
			tripId: "class2.id",
			tripName: "class2.name"
		},
		
		{
			type: 2,
			categoryId: "class1.id",
			categoryName: "class1.name",
			categoryURL: "class1.URL",
			tripName: "trip.name",
			tripURL: "trip.URL"
		}
	]
*/


/*
	As the JSON example illustrates, the travel data array consists of a series of objects.
	This array is broken into two separate arrays: categories and destinations. It is very
	important that these arrays can be sorted alphabetically using the Array.sort() method.
	To achieve this we need to make all the array members instances of the following
	classes. This is because we need to override the Object.toString() method inherited by 
	the members. Otherwise all members would return the string "[object Object]" to the
	Array.sort() method.
*/

function BookerCategory(){
	this.id = null;
	this.name = null;
	this.toString = function(){
		return this.name;
	}
}

function BookerDestination(obj){
	this.trip = obj;
	this.toString = function(){
		return this.trip.tripName;
	}
}



/*
	Integrated Intres booker class
	
	Usage example:
		see matkat/home.jsp & matkat/inc_booker.jsp
	
	Notice:
		travelDataArray must conform to the JSON example above
*/

function IntegratedBooker(travelDataArray){
	/*
		Common URL for all type 1 trips (i.e. trips fetched from the XML).
		Type 2 trips get their URLs as object properties.
	*/
	//this._type1BaseURL = "http://89.166.54.4/scripts/fi/Intres4.dll/OMA_MATKAT?";
	this._type1BaseURL = "http://e-varaukset.lehtimaenmatkat.fi/scripts/fi/Intres4.dll/OMA_MATKAT?";
	this._type1Type = "AS";
	this._type1Country = "FIN";
	
	
	// Form element IDs
	this._formId = "intres_booker";
	this._fTypeId = "fType";
	this._fAgentId = "fAgent";
	this._fUserId = "fUser";
	this._fPassId = "fPass";
	this._fOperId = "fOper";
	this._ddAdultsId = "ddAdults";
	this._ddChildrenId = "ddChildren";
	this._ddInfantsId = "ddInfants";
	this._ddDateId = "ddDate";
	this._ddMonthId = "ddMonth";
	this._ddCategoryId = "ddCategory";
	this._ddDestinationId = "ddDestination";
	this._ddFilterId = "ddFilter";
	
	
	// Internal arrays
	this._travelDataArray = travelDataArray;
	this._categories = null;
	this._currentDestinations = null;
	
	this._formEmts = null; // Object to hold all form elements
	
	
	
	/*
		Clear drop down options
			@ddEmt  : Select element
			@offset	: Amount of option elements to remain inside the select
	*/
	this.clearDropDown = function(ddEmt, offset){
		for(var i = (ddEmt.options.length - 1); i >= offset; i--){
			ddEmt.removeChild(ddEmt.options[i]);
		}
	}
	
	// Get a category matching the given id
	this.getCategoryById = function(catId){
		var found = false;
		if(this._categories.length > 0){
			for(var i = 0; i < this._categories.length; i++){
				if(this._categories[i].id == catId){
					found = this._categories[i];
					break;
				}
			}
		}
		return found;
	}
	
	// Get a destination matching the given name
	this.getDestinationByName = function(destName){
		var found = false;
		if(this._currentDestinations.length > 0){
			for(var i = 0; i < this._currentDestinations.length; i++){
				if(this._currentDestinations[i].trip.tripName == destName){
					found = this._currentDestinations[i];
					break;
				}
			}
		}
		return found;
	}
	
	// Get all destinations from a given category
	this.getDestinationsByCategory = function(catId){
		this._currentDestinations = new Array();
		
		for(var i = 0; i < this._travelDataArray.length; i++){
			if(this._travelDataArray[i].categoryId == catId && this.getDestinationByName(this._travelDataArray[i].tripName) == false){
				this._currentDestinations.push(new BookerDestination(this._travelDataArray[i]));
			}
		}
		
		this._currentDestinations.sort();
	}
	
	
	
	
	
	// Update categories
	this.updateCategories = function(){
		this.clearDropDown(this._formEmts.category, 1);
		
		this._categories = new Array();
		
		var categNames = "";
		
		for(var i = 0; i < this._travelDataArray.length; i++){
			var obj = this._travelDataArray[i];
			
			if(this._categories.length == 0 || this.getCategoryById(obj.categoryId) == false){
				var categ = new BookerCategory();
				categ.name = obj.categoryName;
				categ.id = obj.categoryId;
				this._categories.push(categ);
			}
		}
		
		this._categories.sort();
		
		for(var i = 0; i < this._categories.length; i++){
			var opt = document.createElement("option");
			opt.value = this._categories[i].id;
			var optText = document.createTextNode(this._categories[i].name);
			
			opt.appendChild(optText);
			this._formEmts.category.appendChild(opt);
		}
	}
	
	
	// Update destinations drop down
	this.updateDestinations = function(){
		this.clearDropDown(this._formEmts.destination, 1);
		
		for(var i = 0; i < this._currentDestinations.length; i++){
			var opt = document.createElement("option");
			var optText = document.createTextNode(this._currentDestinations[i].trip.tripName);
			
			opt.appendChild(optText);
			this._formEmts.destination.appendChild(opt);
		}
	}
	
	
	// Run necessary updates when switching categories
	this.selectCategory = function(selectEmt){
		var category = selectEmt.options[selectEmt.selectedIndex].value;
		if(category != ""){
			this.getDestinationsByCategory(category);
			this.updateDestinations();
		}
	}
	
	
	
	/*
		This method is called automatically during instantiation.
		It doesn't really do much - just picks the required elements from the DOM using JTK.
	*/
	this.init = function(){
		this._formEmts = new Object();
		this._formEmts.form = jtk.select("#" + this._formId)[0];
		this._formEmts.type = jtk.select("#" + this._fTypeId)[0];
		this._formEmts.agent = jtk.select("#" + this._fAgentId)[0];
		this._formEmts.user = jtk.select("#" + this._fUserId)[0];
		this._formEmts.pass = jtk.select("#" + this._fPassId)[0];
		this._formEmts.oper = jtk.select("#" + this._fOperId)[0];
		this._formEmts.adults = jtk.select("#" + this._ddAdultsId)[0];
		this._formEmts.children = jtk.select("#" + this._ddChildrenId)[0];
		this._formEmts.infants = jtk.select("#" + this._ddInfantsId)[0];
		this._formEmts.date = jtk.select("#" + this._ddDateId)[0];
		this._formEmts.month = jtk.select("#" + this._ddMonthId)[0];
		this._formEmts.category = jtk.select("#" + this._ddCategoryId)[0];
		this._formEmts.destination = jtk.select("#" + this._ddDestinationId)[0];
		this._formEmts.filter = jtk.select("#" + this._ddFilterId)[0];
	}
	
	
	// Add new travel data into the travel data array (used to insert type 2 trips).
	// Call this method before building the categories!
	this.addData = function(newData){
		if(typeof(newData) == 'object'){
			this._travelDataArray = this._travelDataArray.concat(newData);
		}
	}
	
	// Build category drop down
	this.build = function(){
		this.updateCategories();
	}
	
	
	
	// Submit parameters to the appropriate booking system
	this.submitForm = function(){
		if(this._formEmts.category.selectedIndex > 0){
			var destIndex = this._formEmts.destination.selectedIndex - 1;
			var intresBooker = new IntresBooker();
			
			intresBooker.adults = this._formEmts.adults.value;
			intresBooker.children = this._formEmts.children.value;
			intresBooker.infants = this._formEmts.infants.value;
			intresBooker.filter = this._formEmts.filter.value + "&Valittu_Paiva=" + this._formEmts.date.value + "&Valittu_Kuukausi=" + this._formEmts.month.value;

			if(destIndex >= 0){
				var destination = this._currentDestinations[destIndex].trip;	
				
				if(destination.type != 1){
					intresBooker.baseAddr = destination.tripURL.replace(/&amp;/g, "&");
					intresBooker.type = "AG"; // Set IntresBooker to agent mode
				}
				
				intresBooker.openBooker(this._formEmts.category.value, destination.tripId, "");
			}
			else{
				var destination = this._currentDestinations[0].trip;
				
				if(destination.type != 1){	
					intresBooker.baseAddr = destination.categoryURL;
					intresBooker.type = "AG"; // Set IntresBooker to agent mode
				}
				
				intresBooker.openBooker(this._formEmts.category.value, "", "");
			}
		}
	}
	
	
	this.init();
}
