// used to trigger calendar functions
window.martinair_locale = 'nl_NL';
window.calendarPages = 2;

if ('%d/%m/%Y'.split("/")[0] == "%d") {
  bypass_us_format = true;
}

function getTotalNumberRoomsSelected(scopeElement) {
	var total = 0;
	$(scopeElement).select("select").each(function(element) {
		total += parseInt($F(element));
	});
	return total;
}

function validateRoomSelection(event, formObj) {
	var totalRooms = getTotalNumberRoomsSelected(formObj);
	if (totalRooms == 0) {
		// if the user hasn't selected any value - just select the first room type to 1 room and continue
		var selectToChange = $(formObj).select("select")[0];
		selectToChange.selectedIndex = 1;
		eval(selectToChange.readAttribute('onchange'));
		return true;
	} else {
		return true;
	}
}

function clearElement(id, text) {
	elem = $(id);
	if ( elem ) {
		elem.innerHTML = text;
	}
}


function customerServiceLightbox(event) {
	showLightbox(event, {title: 'iSeatz Service Centre', content: 'Mocht u vragen hebben of problemen ondervinden bij het online boeken van uw reservering, dan kunt u contact opnemen met het iSeatz Service Centre op: <a href=\"mailto:martinair-support@iseatz.com\">martinair-support@iseatz.com<\/a> of +31 20 206 8833. <br /><br /> De details van een bestaande reservering kunt u hier <a href=\"/trips/find\">here<\/a> bekijken. <br /><br />Met vriendelijke groet, het iSeatz Customer Care Team', width: 400, height: 175});
}

function validateSearchDate(event, searchFieldId) {
	searchValue = $F(searchFieldId);
  if (!searchValue.match(/\d{1,2}\/\d{1,2}\/\d{4}/)) {
		showLightbox(event, {title: 'Notice', content: 'Please enter dates in the format mm/dd/yyyy.', width: 400, height: 175})
    return false;
  }
	return true;
}

function enableSerializedRoom(selectObj, roomId) {
	if (selectObj.selectedIndex == 0) {
		$('room_obj_' + roomId).disabled = 'true'
	} else {
		$('room_obj_' + roomId).removeAttribute('disabled');
	}
}

function updateSelectedHotelRates(hotelId, hotelRoomId, numberOfRooms, rate) {
	$('selected_room_rates_' + hotelRoomId).value = numberOfRooms * rate;
	var totalRate = 0;
	$('hotel_form_' + hotelId).select('input.selected_room_total').each(function(element) {
			totalRate += parseFloat(element.value);
	});
	if (!isNaN(totalRate) ) {
		$(hotelId + '_price_est').innerHTML = totalRate.toFixed(2);
	}
}

function showLightbox(event, options) {
	var lb = new Lightbox({container: 'lightbox', width: options['width'] ? options['width'] : 500, height: options['height'] ? options['height'] : 350, title: options['title'], lightbox_id: options['lightbox_id']});
	if (options['content']) lb.setContent(options['content']);
	lb.show(event);
	return lb;
}

function updateHotelSearchOptions(locationType, selectedValue) {
	removeChildNodes($('search_radius'));
 	if (locationType == 'City' || locationType == 'Airport') {
		['Alle afstanden','1 kilometer vanaf het centrum', '5 kilometer vanaf het centrum', '15 kilometer vanaf het centrum'].each(function(val, i) {
			var value = 'City,' + hotelCityDistances[i];
			if (i == 0) {
				value = '';
			}
			$('search_radius').appendChild(new Element('option', {'value': value, 'selected': selectedValue == value ? true : false}).update(val));
		});
	} 
	if (locationType == 'Airport') {
		['1 kilometer vanaf de luchthaven', '5 kilometer vanaf de luchthaven', '15 kilometer vanaf de luchthaven'].each(function(val, i) {
			var value = 'Airport,' + hotelAirportDistances[i];
			$('search_radius').appendChild(new Element('option', {'value': value, 'selected': selectedValue == value ? true : false }).update(val));
		});
	} 
}

function updateFeatureHotelImage(selectedImg, url) {
	$('featured_image').src = url;
	$('thumbs').select('img').each(function(img) {
		img.removeClassName('selected');
	});
	selectedImg.addClassName('selected');
}

function isDifferentDropoff(event) {
  if (event.element().value == 'different') {
    if ($F('car_search_start_location_search') == $F('car_search_end_location_search')) {
        $('car_search_end_location_search').value = '';
        $('eclid').value = '';
    }
    $('car_search_end_location_search').show();
    $('car_search_end_location_search').focus();
  } else {
    if ($F('car_search_start_location_search') != $F('car_search_end_location_search')) {
      $('car_search_end_location_search').value = '';
      $('eclid').value = '';
    }
    $('car_search_end_location_search').hide();
  }
}

function carSortByPrice(carNodeA, carNodeB) {
	return carNodeA.getAttribute('price') - carNodeB.getAttribute('price');
}

function carSortBySeats(carNodeA, carNodeB) {
	return carNodeB.getAttribute('seats') - carNodeA.getAttribute('seats');
}

function carSortByLuggage(carNodeA, carNodeB) {
	return carNodeB.getAttribute('luggage') - carNodeA.getAttribute('luggage');
}

function carSortByDoors(carNodeA, carNodeB) {
	return carNodeB.getAttribute('doors') - carNodeA.getAttribute('doors');
}

function sortCarResults(select) {
	var pluckAttribute = carSortTypes[select.selectedIndex];
	var currentNodeOrder = new Array();
	var valuesToSort = new Array();
	$('car_results').select('div.sort_worker').each(function(car_div, i) {
		currentNodeOrder.push(car_div);
	});
	if (pluckAttribute != 'price') {
		currentNodeOrder = currentNodeOrder.reverse();
	}
	removeChildNodes($('car_results'));
	switch (pluckAttribute) {
		case 'price':
			currentNodeOrder.sort(carSortByPrice);
			break;
		case 'seats':
			currentNodeOrder.sort(carSortBySeats);
			break;
		case 'luggage':
			currentNodeOrder.sort(carSortByLuggage);
			break;
		case 'doors':
			currentNodeOrder.sort(carSortByDoors);
			break;
	}
	for (var i = 0; i < currentNodeOrder.length; i++) {
		$('car_results').appendChild(currentNodeOrder[i])
	}
}

function propagateNameFields(nameType, obj) {
	switch(nameType) {
		case 'FIRST':
			$('customer_card_first_name').value = obj.value;
			if (window.firstHotelRoomId) {
				$('hotel_room_' + firstHotelRoomId + '_guest_first_name').value = obj.value;
			}
			if (window.firstCarReservationId) {
				$('car_reservation_' + firstCarReservationId + '_driver_first_name').value = obj.value;				
			}
			break;
		case 'LAST':
			$('customer_card_last_name').value = obj.value;
			if (window.firstHotelRoomId) {
				$('hotel_room_' + firstHotelRoomId + '_guest_last_name').value = obj.value;
			}
			if (window.firstCarReservationId) {
				$('car_reservation_' + firstCarReservationId + '_driver_last_name').value = obj.value;				
			}
			break;			
	}
}

function validateCarSearchLocation() {
  var searchValue = $('car_search_start_location_search').value;
  var locationIdValue = $('sclid').value;
  if ((locationIdValue == null || locationIdValue == '' || locationIdValue.length == 0) && (searchValue == '')) {
	removeChildNodes($('dom_errors'));
	$('dom_errors').insert('<p class="dom_error">A car rental pick up location is required.</p>')
    return false;
  } else if ((locationIdValue == null || locationIdValue == '' || locationIdValue.length == 0) && (searchValue != '')){
	removeChildNodes($('dom_errors'));
	$('dom_errors').insert('<p class="dom_error">You must select a car rental location from the list below.</p>')
	setTimeout(function() {car_search_start_location_search_auto_completer.activate();}, 250);
    return false;
  } else {
    return true;
  }
}

function validateHotelSearchLocation() {
  var searchValue = $('hotel_search_search_location').value;
  var locationIdValue = $('lid').value;
  if ((locationIdValue == null || locationIdValue == '' || locationIdValue.length == 0) && (searchValue == '')) {
	removeChildNodes($('dom_errors'));
	$('dom_errors').insert('<p class="dom_error">A hotel destination is required.</p>')
    return false;
  } else if ((locationIdValue == null || locationIdValue == '' || locationIdValue.length == 0) && (searchValue != '')){
	removeChildNodes($('dom_errors'));
	$('dom_errors').insert('<p class="dom_error">You must select a city or airport location from the list below.</p>')
	setTimeout(function() {hotel_search_search_location_auto_completer.activate();}, 250);
    return false;
  } else {
    return true;
  }

}

function validateSearchDate(searchFieldId) {
  var searchValue = $F(searchFieldId);
  if (!searchValue.match(/\d{1,2}\/\d{1,2}\/\d{4}/)) {
    alert('Please enter dates in the format dd/mm/yyyy.');
    return false;
  }
	return true;
}

function pickCardType(cardType, skipReset) {
    $(cardType).insert($('card_fields'), {position: 'after'});
    
    if (!skipReset) {
        $('customer_cvv_code').value='';
        $('customer_card_expiration_month').value='';
        $('customer_card_expiration_year').value='';
    }
}

/* lookup tables */
var hotelSortOrders = {'0': 'ASC', '1': 'DESC', '2': 'ASC', '3': 'DESC', '4': 'ASC', '5': 'DESC', '6': 'DESC'}
var hotelCityDistances = ['', 1, 5, 15];
var hotelAirportDistances = [1, 5, 15];
var carSortTypes = {0: 'price', 1: 'seats', 2: 'luggage', 3: 'doors'}

var centeredSpinner = '<div class="center"><img src="/images/klm/search-spinner.gif" /></div>'



function redirect_to(url) {
	window.location = url;
}


function Lightbox(options) {
	this.width = options['width'];
	this.height = options['height'];
	var classAttribute = isIE ? 'className' : 'class';
	
	var d = ce("div");
	
	var lightbox_id = options['lightbox_id']
	if ( lightbox_id && lightbox_id !== '' ) {
		if ( document.getElementById(lightbox_id) != null ) {
			return;
		}
		d.setAttribute('id', lightbox_id);
	}
	
//	d.setAttribute('style', "width: " + this.width);
	d.setAttribute(classAttribute,'dialog wide');
	
	var divHead = ce('div');
	divHead.setAttribute(classAttribute,'title');
	var divClose = ce('div');
	var a = ce('a');
	a.setAttribute('href','#');
	a.setAttribute(classAttribute, 'close')
	Event.observe(a, 'click', function(event) {this.hide(event);}.bind(this));
	a.innerHTML = '&#215;'
	
	var h2 = ce('h2');
	h2.appendChild(document.createTextNode(options['title']));

	divClose.appendChild(a);
	divClose.appendChild(h2);
	divHead.appendChild(divClose);
	
	d.appendChild(divHead);
	
	var divCenter = ce('div');
	divCenter.setAttribute(classAttribute, 'con clearfix');
	var divCenterInner = ce('div');
	divCenterInner.setAttribute(classAttribute, 'innerCon clearfix');
	divCenterInner.setAttribute('id', 'lightbox_content');
	divCenter.appendChild(divCenterInner);
	
	d.appendChild(divCenter);
	
	var divFooter = ce('div');
	divFooter.setAttribute(classAttribute, 'b');
	var divFooterInner = ce('div');
	divFooter.appendChild(divFooterInner);
	d.appendChild(divFooter);
		
	$(options['container']).appendChild(d);
}
