// collection of objects.
function Collection()
{
	this.type = "";
  this.items = new Array();
	this.count = 0;
  this.add = addCollectionItem;
	this.get = getCollectionItem;

	// Adds an item (object) to the collection.
	// item: The object to add
	// remark: Only objects of class specified in this.type are allowed.
  function addCollectionItem(item)
  {
		var className = /(\w+)\(/.exec(item.constructor.toString())[1];
		if(className == this.type && item.id)
		{
			this.items[this.count] = item;
			this.count++;
		}
		else
		{
			if(item.id)alert('Collection.add Error\nOnly >' + this.type + '< allowed!');
			else alert('Collection.add Error\nItem has no >Id< Property!');
		}
  }

  // Get an object from the collection by object.id;
  function getCollectionItem(id)
  {
		var item = null;
		for(i=0;i<this.count;i++)
		{
			if(this.items[i].id == id)
			{
				item = this.items[i];
			}
		}
		return item;
  }
}

/* Prices */
function Price(id, type, caption, value, formatedValue)
{
  this.id = id;
  this.type = type;
  this.caption = caption;
  this.value = value;
  this.formatedValue = formatedValue;
  this.formatPrice = formatPrice;

	function formatPrice(strValue, currency)
	{
		var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');
		switch(currency)
		{
		  case '€':
		    strValue = strValue + ' €';
        break;
		  case '£':
		    strValue = '£' + strValue;
        break;
		  case '$':
		    strValue = '$ ' + strValue;
        break;
		  default:
		    strValue = strValue + ' ' + currency
        break;
		}
		strValue = strValue.replace('.', ',');

		//check for match to search criteria
		while(objRegExp.test(strValue))
		{
				//replace original string with first group match,
				//a comma, then second group match
				strValue = strValue.replace(objRegExp, '$1.$2');
		}
		return strValue;
	}      
}

// Collection of Price elements. Derived from Collection.
function Prices()
{
  this.items = new Array();
	this.type = "Price";
	this.sum = sumPrices;
  this.currency = '€';

  function sumPrices()
  {
		var price = 0;
		for(i=0;i<this.count;i++)
		{
			price += this.items[i].value;
		}
		
		price = new Price('sum', null, null, price, null);
		price.formatedValue = price.formatPrice(price.value, this.currency);
		return price;
		//return price;
  }
}
Prices.prototype = new Collection;

/* Options */
function FormOption(id, caption, description, price)
{
  this.id = id;
  this.caption = caption;
  this.description = description;
  this.price = price;
}

// Collection of FormOption elements. Derived from Collection.
function FormOptions()
{
  this.items = new Array();
	this.type = "FormOption";
}
FormOptions.prototype = new Collection;

// Helper Methods for handling forms
function FormHelper(formName)
{
	this.name = formName; // Set/Get the Name of the form
	this.get = getElement; 
	this.enable = enableElement;
	this.disable = disableElement;
	this.value = getFormValue; // Get the value of an form element
	this.attachToEvent = attachToEvent;
	
  // enables a form element.
  // elementName: name of the form element
  // remark: The className of the table with id table_[elementName] will be assigned to formsfield
	function enableElement(elementName)
	{
    var table = this.get('table_' + elementName);
    var element = this.get(elementName);
    if(table)table.className='formsfield';
    if(element)element.disabled=false;
	}

  // Disables a form element.
  // elementName: name of the form element
  // remark: The className of the table with id table_[elementName] will be assigned to disabledformsfield
	function disableElement(elementName)
	{
    var table = this.get('table_' + elementName);
    var element = this.get(elementName);
    if(table)table.className='disabledformsfield';
    if(element)
    { element.disabled=true;
		  if(element.selectedIndex)element.selectedIndex = 0;
		}
	}
	
  // Get a form element.
  // elementName: name of the form element
  function getElement(elementName)
  {
    var element = null;
    element = document.getElementById(elementName);
		if(!element)element = eval('document.forms["' + this.name + '"].' + elementName);
		return element;
	}
	
  // Get the value of a form element.
  // elementName: name of the form element
  function getFormValue(elementName)
  {
		formElement = eval('document.forms["' + this.name + '"].' + elementName);
		if(formElement)
		{
		  if(formElement.length != null)var type = formElement[0].type;
		  if((typeof(type) == 'undefined') || (type == 0)) var type = formElement.type;

		  switch(type)
		  {
			  case 'undefined': return;

			  case 'radio':
				  for(var x=0; x < formElement.length; x++) 
					  if(formElement[x].checked == true)
				  return formElement[x].value;

			  case 'select-multiple':
				  var myArray = new Array();
				  for(var x=0; x < formElement.length; x++) 
					  if(formElement[x].selected == true)
						  myArray[myArray.length] = formElement[x].value;
				  return myArray;

			  case 'checkbox': return formElement.checked;
  		
			  default: return formElement.value;
		  }
		}
	}

  function attachToEvent(obj,eventToAttach,functionToAdd)
  {
	  var oldEvent = (eval('obj.' + eventToAttach)) ? eval('obj.' + eventToAttach) : function () {};
	  eval('obj.' + eventToAttach + ' = function(){oldEvent();functionToAdd();}')
  }
}

function DrivingSchoolContanier(formName)
{
	this.name = formName;
	this.selectParticipants = selectParticipants;
	this.selectPaticipateCarType = selectPaticipateCarType;
	this.selectHotelBooking = selectHotelBooking;
	this.selectHotel = selectHotel;
	this.calcPrice = calcPrice;
	this.init = init;
	this.currency = '€';
	this.hotels = null;
	this.rentCars = null;
  this.basePrice = null;
	this.personalTrainerPrices = null;
	this.participantPrices = null;
	this.totalPriceElementname = 'training_totalprice';

	function init()
	{
	  var obj = this;
		var initFunction = function()
		{
			obj.selectPaticipateCarType();
			obj.selectParticipants();
			obj.selectHotelBooking();
			obj.calcPrice();
    }
		obj.attachToEvent(window,'onload',initFunction);
	}
	
  function selectParticipants()
  {
		var persons = this.value('drivingschool2_participants')
    if(persons != '0')
    {
      this.enable('drivingschool2_firstname');
      this.enable('drivingschool2_lastname');
    }
    else
    {
      this.disable('drivingschool2_firstname');
      this.disable('drivingschool2_lastname');
    }
    this.selectHotelBooking();
  }

  function selectPaticipateCarType()
  {
		var selectedCar = null;
		sfsCarElement = this.get('drivingschool2_sfscar')
		if(sfsCarElement)
		{
			/*
			document.forms["formcontrol"].drivingschool2_sfscar.length = 1;
			document.forms["formcontrol"].drivingschool2_sfscar.selectedIndex = 0;
			for(i=0;i<this.rentCars.count;i++)
			{
				selectedCar = this.rentCars.items[i];
				newValue = new Option(selectedCar.caption + ' - ' + selectedCar.price.formatedValue + ' ' + selectedCar.price.caption, selectedCar.id, false, false);
				document.forms["formcontrol"].drivingschool2_sfscar.options[document.forms["formcontrol"].drivingschool2_sfscar.length] = newValue;
			}
			*/

			var currentCarType = this.value('drivingschool2_paticipatecartype');
			switch(currentCarType)
			{
				case 'rent':
					this.enable('drivingschool2_sfscar');
					this.disable('car_make');
					this.disable('car_model');
					this.disable('car_type');
					this.disable('car_modelyear');
					this.disable('car_licencenumber');
					this.disable('car_power');
					break;
				case 'own':
					this.disable('drivingschool2_sfscar');
					this.enable('car_make');
					this.enable('car_model');
					this.enable('car_type');
					this.enable('car_modelyear');
					this.enable('car_licencenumber');
					this.enable('car_power');
					break;
				default:
					this.disable('drivingschool2_sfscar');
					this.disable('car_make');
					this.disable('car_model');
					this.disable('car_type');
					this.disable('car_modelyear');
					this.disable('car_licencenumber');
					this.disable('car_power');
					break;
			}
    }
  }

  function selectHotel()
  {
	  var selectedHotel;
		var price;
		if(this.get('drivingschool2_hotel'))
		{
			var participants = this.value('drivingschool2_participants');
			curHotelId = this.value('drivingschool2_hotel');
			selectedHotel = this.hotels.get(curHotelId);
			hotelRoomOne = this.get('drivingschool2_hotelroomone');
			hotelRoomTwo = this.get('drivingschool2_hotelroomtwo');
			if(selectedHotel)
			{
	      this.enable('drivingschool2_hotelroomone');
        if(participants != '0')this.enable('drivingschool2_hotelroomtwo');
        else this.disable('drivingschool2_hotelroomtwo');

				if(hotelRoomOne)hotelRoomOne.length = 1;
				if(hotelRoomTwo)hotelRoomTwo.length = 1;
				for(i=0;i<selectedHotel.price.count;i++)
				{
					price = selectedHotel.price.items[i];
					newValue = new Option(price.caption + ' - ' + price.formatedValue, price.id, false, false);
					switch(price.type)
					{
						case 'hotelroomone':
							if(hotelRoomOne)hotelRoomOne.options[hotelRoomOne.length] = newValue;
							break;
						case 'hotelroomtwo':
							if(hotelRoomTwo)hotelRoomTwo.options[hotelRoomTwo.length] = newValue;
							break;
					}
				}
			}
			else
			{
        if(participants == '0')this.disable('drivingschool2_hotelroomtwo');
				if(hotelRoomOne)hotelRoomOne.length = 1;
				if(hotelRoomTwo)hotelRoomTwo.length = 1;
        this.disable('drivingschool2_hotelroomone');
        this.disable('drivingschool2_hotelroomtwo');
			}
    }
  }

  function selectHotelBooking()
  {
    var booking = this.value('drivingschool2_hotelbooking');
    var participants = this.value('drivingschool2_participants');
    switch(booking)
    {
      case 'yes':
        this.enable('drivingschool2_hotel');
        break;
      default:
        this.disable('drivingschool2_hotel');
        break;
    }
    this.selectHotel();
  }

  function calcPrice()
  {
    var prices = new Prices();
		var price = null;

		prices.currency = this.currency;

    prices.add(new Price('base', null, null, this.basePrice));
    
		/* calculate participants */
		var currentParticipants = this.value('drivingschool2_participants');
		if(currentParticipants && currentParticipants != '0')
		{
			price = null;
			price = this.participantPrices.get(currentParticipants);
      if(price)prices.add(new Price(currentParticipants, null, null, price.value));
		}

		/* calculate car */
		var currentCarType = this.value('drivingschool2_paticipatecartype');
		if(currentCarType && currentCarType == 'rent')
		{
			price = null;
			var selectedCar = this.value('drivingschool2_sfscar');
			if(selectedCar && selectedCar != '')price = this.rentCars.get(selectedCar);
      if(price)
      {
				price = price.price
				prices.add(new Price(selectedCar, null, null, price.value));
      }
		}

		/* calculate personal trainer */
		var currentPT = this.value('drivingschool2_personaltrainer')
		if(currentPT && currentPT != '')
		{
		  price = this.personalTrainerPrices.get(currentPT)
			if(price)prices.add(price);
		}
		
		sum = prices.sum()
		this.get(this.totalPriceElementname).innerHTML=sum.formatedValue;
  }
      
	/************************************************
	DESCRIPTION: Inserts commas into numeric string.

	PARAMETERS:
		strValue - source string containing commas.

	RETURNS: String modified with comma grouping if
		source was all numeric, otherwise source is
		returned.

	REMARKS: Used with integers or numbers with
		2 or less decimal places.
	*************************************************/
}
DrivingSchoolContanier.prototype = new FormHelper(DrivingSchoolContanier.name)
