var quickSearch = null;
var SS = null;
var BO = null;
var HIS = null;
var PD = null;

/*	-- HELPER FUNCTIONS ------------------------------------------------------- */
function closeColorBox() {	
	$.fn.colorbox.close();
}

function ajaxError() {
    closeColorBox();
    alert(ol_CommunicationsError);
}

function handleBookingError(errorCode, errorMessage, payments) {
	var errMsg = "";

	if (errorCode == 39) {
		errMsg =  payments[0].ErrorMessage + ' (' + ol_BookingError_Code + ': ' + payments[0].ErrorCode + ')';
 	} else {
		errMsg = errorMessage + ' (' + ol_BookingError_Code + ': ' + errorCode + ')';
	}

	$('#booking_loader').hide();
	$('#booking_error').show();
	$('#error_message').html(errMsg);
}

function getCurrentPage () {
	var currentPage = null;
	currentPage = window.location.href.replace('https://', '');
	currentPage = currentPage.replace('http://', '');
	currentPage = currentPage.replace('?', '#');
	
	if (currentPage.indexOf("#") > 0) {
		currentPage = currentPage.substring(currentPage.indexOf('/'),currentPage.indexOf("#"));
	} else {
		currentPage = currentPage.substring(currentPage.indexOf('/'));
	}

	return currentPage.toLowerCase();
}

var loadDates = function LoadDates() {
	// GET OBJECTS:
	var from = $('#qs_departure_destination_id').val();
	var to = $('#qs_arriving_destination_id').val();
  
	// GET DEPARTURES:
	if (from.length > 0 && to.length > 0) {
		$('#qs_date_from').empty();
		$('#qs_date_from').append('<option value="">' + ol_LoadingDates + '</option>');		
		Odin.Modules.Support.OdinAPI.GetDepartureDates($('#qs_owner_info').val(), from, to, function(r) {
			quickSearch.loadDepartures(r);
		}, Error);
	}

	// GET ARRIVALS:
	if (from.length > 0 && to.length > 0) {
		$('#qs_date_to').empty();
		$('#qs_date_to').append('<option value="">' + ol_LoadingDates + '</option>');
		Odin.Modules.Support.OdinAPI.GetDepartureDates($('#qs_owner_info').val(), to, from, function(r) {
			quickSearch.loadArrivals(r);
		}, Error);
	}
};

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}

function getCurrentCategory () {	
	  var currentPage = null;
	  var currentPageArr = new Array();
	  currentPage = window.location.href.replace('https://', '');
	  currentPage = currentPage.replace('http://', '');
	  if (currentPage.indexOf("#") > 0) {
	    currentPage = currentPage.substring(currentPage.indexOf('/'),currentPage.indexOf("#"));
	  } else {
	    currentPage = currentPage.substring(currentPage.indexOf('/'));
	  }
	  currentPageArr = currentPage.replace('/','').trim().split("/"); 
	  return currentPageArr[0].toLowerCase();
}

/*	-- QUICK SEARCH ----------------------------------------------------------- */
QuickSearch = function() {
	this.init();
};
jQuery.extend(QuickSearch.prototype, {
	init: function() {
		this.departures = null;
		this.arrivals = null;
		this.fromSelect = $('#qs_date_from');
		this.toSelect = $('#qs_date_to');
		this.currentDateFrom = null;
		this.currentDateTo = null;
		this.ownerInfo = $('#qs_owner_info').val();
		this.ownerID = this.ownerInfo.split('|')[0];
		this.serviceCategoryID = 0;
		this.serviceID = 0;
		this.hotelDestinationID = 0;
		this.DestinationID = 0;
		this.urls = '';
		this.searchType = 'Departures';
		this.freezeElements = false;
		this.iframeSearch = false;
		this.hasLoadedData = false;

		this.hideAll();
		this.loadCookieData();
		this.loadSelectedDestinations();
	},
	loadCookieData: function() {
		var count = 0;
		
		var c = $.cookieJar('ODIN-BOOKING-DATA', {
			path: '/',
			expires: 7,
			cookiePrefix: ''
		});

		if (c) {
			$('#qs_adult_count').val(c.get('adult_count'));
			$('#qs_child_count').val(c.get('child_count'));
			$('#qs_infant_count').val(c.get('infant_count'));
			$('#qs_arriving_destination_id').val(c.get('arrival_destination_id'));
			$('#qs_departure_destination_id').val(c.get('departure_destination_id'));
			
			if (c.get('departure_date') && c.get('departure_date').length > 0 && c.get('departure_date') != '1999-12-31') {
				$('#qs_datepicker_from').val(c.get('departure_date'));
			}

			if (c.get('arrival_date') && c.get('arrival_date').length > 0 && c.get('arrival_date') != '1999-12-31') {
				$('#qs_datepicker_to').val(c.get('arrival_date'));
			}

			this.urls = c.get('urls');
			this.searchType = c.get('search_type');
			this.hasLoadedData = true;
			
			if(this.searchType == 'Packages') {
				$('#qs_packagecategory_id > option[value='+ c.get('package_category_id') +']').attr('selected','selected');
				this.loadPackages(c.get('package_category_id'));                       
			}
		}
	},
	hideAll: function() {
		$('.qs-module').hide();
	},
	showItem: function(item) {
		$('#' + item).show();
	},
	setUrls: function(inUrls) {
		this.urls = inUrls;
	},
	loadSelectedDestinations: function() {
	    if (!this.freezeElements) {
			var c = $.cookieJar('ODIN-BOOKING-DATA', {
				path: '/',
				expires: 7,
				cookiePrefix: ''
			});			
		}
	},
	loadDepartures: function(obj) {
		this.departures = obj;		
		var from = this.fromSelect;

		$(from).empty();
		from.attr("disabled",false);

		if (this.departures.length > 0) {
			from.append('<option value="">-- ' + ol_SelectDate + ' --</option>');
			jQuery.each(this.departures,function(i,item) {
				var text = item.FormattedDate;
				
				if (item.AvailableSeatCount < 1) {
					text += ' - ' + ol_SoldOut;
				} else if (item.AvailableSeatCount >= 1 && item.AvailableSeatCount < 7) {
					text += ' - ' + item.AvailableSeatCount + ' ' + ol_SeatsAvailable;
				}
                from.append( '<option value="' + item.FlightID + ':' + item.ValueDate + ':' + item.AvailableSeatCount + '">' + text + '</option>' );
			});
			
			var c = $.cookieJar('ODIN-BOOKING-DATA', {
				cookiePrefix: ''
			});
			
			if (c !== null && c.get('departure_flight_id') !== null) {		      
				for (i = 1; i < from[0].options.length; i++) { 
					if (from[0].options[i].value.split(':')[0] == c.get('departure_flight_id') && from[0].options[i].value.split(':')[1] == c.get('departure_date')) {  
						this.currentDateFrom = c.get('departure_date');	
						$(from[0].options[i]).attr("selected", "selected");			  
						break;
					}					
				}
					
				from.value = c.get('departure_flight_id') + ':' + c.get('departure_date');
				this.currentDateFrom = from.value;
			}                                                 
		} else {
			from[0].options[from[0].options.length] = new Option('Enginn flug', '');
		}
	},
	loadArrivals: function(obj) {
		this.arrivals = obj;
		var to = this.toSelect;

		$(to).empty();
		to.attr("disabled",false);

		if (this.arrivals.length > 0) {
			to.append('<option value="">-- ' + ol_SelectDate + ' --</option>');

			jQuery.each(this.arrivals,function(i,item) {
				var text = item.FormattedDate;
				
				if (item.AvailableSeatCount < 1) {
					text += ' - ' + ol_SoldOut;
				} else if (item.AvailableSeatCount >= 1 && item.AvailableSeatCount < 7) {
					text += ' - ' + item.AvailableSeatCount + ' ' + ol_SeatsAvailable;
				}
				to.append('<option value="' + item.FlightID + ':' + item.ValueDate + ':' + item.AvailableSeatCount + '">'+ text +'</option>');
			});

			var c = $.cookieJar('ODIN-BOOKING-DATA', {cookiePrefix: ""});
			if (c !== null && c.get('arrival_flight_id') !== null) {		
				for (i = 1; i < to[0].options.length; i++) {
					if (to[0].options[i].value.split(':')[0] == c.get('arrival_flight_id') && to[0].options[i].value.split(':')[1] == c.get('arrival_date')) {
						this.setToDate(c.get('arrival_date'));
						$(to[0].options[i]).attr("selected", "selected");						
						break;
					}					
				}

				to.value = c.get('arrival_flight_id') + ':' + c.get('arrival_date');
				this.currentDateTo = to.value;
			}
		} else {
			to[0].options[to[0].options.length] = new Option(ol_NoFlights, '');
		}
	},
	reloadArrivals: function() {
		if (this.Arrivals !== null) {
			this.loadArrivals(this.Arrivals);
		}
	},
	setFromDate: function(date) {
		this.currentDateFrom = date;
	},
	setToDate: function(date) {
		this.currentDateTo = date;
	},
	loadPackages: function(categoryID) {
		if (categoryID != null) {
			Odin.Modules.Support.OdinAPI.GetPackages(this.ownerInfo, categoryID, function(r) {
				var c = $.cookieJar('ODIN-BOOKING-DATA', {cookiePrefix: ""});
				var selectList = $('#qs_package_id');
				var cookieValue = c.get('package_id');
				selectList.empty();

				if (r.Packages != null) {
					selectList.attr("disabled",false);
					selectList.append('<option value="">-- ' + ol_SelectTour + ' --</option>');
					jQuery.each(r.Packages,function(i,item) {
						selectList.append('<option value="'+ item.GUID + '">' + item.Name + '</option>');  
						
					});
					selectList.children('[value='+ cookieValue +']').attr('selected','selected');
					
				} else {			
					selectList.disabled = true;
					selectList.append('<option value="">' + ol_NoTourFound + '</option>');
				}
			}, Error);
		}
	},
	search: function(url, selectedID) {     
		var c = $.cookieJar('ODIN-BOOKING-DATA', {
			expires: 7,
			path: '/',
			cookiePrefix: ''
		});
		
	 	if(this.searchType == 'Departures') {
	       	// CHECK ON IF BOTH FLIGHTS ARE SELECTED IN FLIGHT AND HOTEL SEARCH:
	  		if ($('#qs_departure_destination_id').val().length === 0) {	  		
	  			alert(ol_err_select_destination);
	  			return;
	  		}
	  		// CHECK ON IF BOTH FLIGHTS ARE SELECTED IN FLIGHT AND HOTEL SEARCH:
	  		if ($('#qs_arriving_destination_id').val().length === 0) {
	  			alert(ol_err_select_destination);
	  			return;
	  		}
	  		// CHECK ON IF BOTH FLIGHTS ARE SELECTED IN FLIGHT AND HOTEL SEARCH:
	  		if( $('#qs_search_type_flight_hotel:checked').length > 0 && (  $('#qs_date_from').val().length === 0 || $('#qs_date_to').val().length === 0 )) {
	  			alert(ol_err_select_both_dates);
	  			return;
	  		}
	  		// CHECK ON IF BOTH FLIGHTS ARE SELECTED IN FLIGHT AND HOTEL SEARCH:
	  		if( (this.currentDateFrom == null || this.currentDateFrom == ":undefined" || this.currentDateFrom == "0:1999-12-31")) {
	  			alert(ol_err_select_both_dates);
	  			return;
	  		}
	  		// CHECK ONE WAY:
	  		if( $('#qs_search_type_flight_only:checked').length > 0 && (this.currentDateTo.substring(0,1) == 0 || this.currentDateTo == "undefined:1999-12-31") ) {
	  			if (!confirm(ol_err_areyousureyouwantoneway)) {
	  				return;
	  			}
	  		}
	  		// CHECK IF THERE IS ENOUGH SEATS ON FLIGHT:
	  		if ( this.currentDateFrom != null) {
	  			if (this.currentDateFrom.split(':')[2] < 1) {
	  				alert(ol_err_flightsoldout);
	  				return;
	  			} else if ((parseInt(this.currentDateFrom.split(':')[2]) - (parseInt($('#qs_adult_count').val()) + parseInt($('#qs_child_count').val()))) < 0 ) {
	  				alert(ol_err_flightsoldout);
	  				return;			
	  			}
	  		}
	  		// CHECK IF THERE IS ENOUGH SEATS ON FLIGHT:
	  		if( this.currentDateTo != null ) {
	  			if (this.currentDateTo.split(':')[2] < 1) {
	  				alert(ol_err_flightsoldout);
	  				return;
	  			} else if ((parseInt(this.currentDateTo.split(':')[2]) - (parseInt($('#qs_adult_count').val()) + parseInt($('#qs_child_count').val()))) < 0 ) {
	  				alert(ol_err_flightsoldout);
	  				return;			
	  			}
	  		}
	  	} else if (this.searchType == 'Packages') {
	  		// CHECK PACKAGE CATEGORY SELECTION:
	  		if( $('#qs_packagecategory_id').get(0).selectedIndex == 0 ) {
	  			alert(ol_err_select_package_category);
	  			return;
	  		}
	  		// CHECK PACKAGE SELECTION:
	  		if ( $('#qs_package_id').get(0).selectedIndex == 0 ) {
	  			alert(ol_err_select_package);
	  			return;
	  		}
  		}

		c.remove();
		c.set('urls', this.urls);
		c.set('owner_id', this.ownerID);
		c.set('adult_count', $('#qs_adult_count').val());
		c.set('child_count', $('#qs_child_count').val());
		c.set('infant_count', $('#qs_infant_count').val());
		c.set('search_type', this.searchType); 
		c.set('package_category_id', '0');
		c.set('package_id', '0');
		c.set('source', getCurrentCategory());
		
		if (this.searchType == 'Standard') {
			c.set('departure_date', $('#qs_datepicker_from').val());
			c.set('arrival_date', $('#qs_datepicker_to').val());
			c.set('arrival_destination_id', $('#qs_arriving_destination_id').val());
			c.set('departure_destination_id', $('#qs_departure_destination_id').val());
			c.set('service_category_id', this.serviceCategoryID);

			c.set('departure_flight_id', 0);
			c.set('arrival_flight_id', '0');
			c.set('flight_only', false);
			c.set('one_way', false);
			
	  	} else if (this.searchType == 'Departures') {
			var from = $('#qs_date_from').val();
	    	var to = $('#qs_date_to').val();

			c.set('departure_flight_id', from.split(':')[0]);
			c.set('departure_date', from.split(':')[1]);

			if ($('#qs_date_to').get(0).selectedIndex > 0) {
				c.set('arrival_flight_id', to.split(':')[0]);
				c.set('arrival_date', to.split(':')[1]);
				c.set('one_way', 'false');
			} else {
				c.set('arrival_flight_id', '0');
				c.set('arrival_date', '1999-12-31');
				c.set('one_way', 'true');
			}

			c.set('departure_destination_id', $('#qs_departure_destination_id').val());
			c.set('arrival_destination_id', $('#qs_arriving_destination_id').val());
			c.set('flight_only', 'false');
                                              
	  	} else if (this.searchType == 'Hotel') {
			var from = $('#qs_datepicker_from').val();
	    	var to = $('#qs_datepicker_to').val();
			c.set('departure_date', from);
			c.set('arrival_date', to);

			c.set('departure_destination_id', 0);
			c.set('arrival_destination_id', this.hotelDestinationID);
			c.set('flight_only', 'false');
		                                          
	  	} else if (this.searchType == 'SingleService') {
			var from = $('#qs_datepicker_from_' + selectedID).val();
	    	var to = $('#qs_datepicker_to_' + selectedID).val();
   			c.set('adult_count', $('#qs_adult_count_' + selectedID).val());
			c.set('child_count', $('#qs_child_count_' + selectedID).val());
			c.set('infant_count', $('#qs_infant_count_' + selectedID).val());
			c.set('departure_date', from);
			c.set('arrival_date', to);
			c.set('departure_destination_id', 0);
			c.set('arrival_destination_id', this.DestinationID);
			c.set('flight_only', 'false');
			c.set('service_category_id', this.serviceCategoryID);
			c.set('service_id', selectedID)
					
		} else if (this.searchType == 'Packages') {
			c.set('departure_date', '1999-12-31');
			c.set('arrival_date', '1999-12-31');
			c.set('arrival_destination_id', 0);
			c.set('departure_destination_id', 0);
			c.set('departure_flight_id', 0);
			c.set('package_category_id', $('#qs_packagecategory_id').val());
			c.set('package_id', $('#qs_package_id').val());
			c.set('package_name', $('#qs_package_id option:selected').text());
		}

  		if (!this.iframeSearch) {
			top.window.location.href = url;
		} else {
			top.location.href = url;
		}
	}
});


/*	PACKAGE PAGE:
--------------------------------------------------------------------------------------------------------------------- */
var _thisPD = null;
PackageDetails = function(id, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL, currencyCode) {
	this.init(id, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL, currencyCode);
};
jQuery.extend( PackageDetails.prototype, {
	init: function(id, guid, type, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems, startURL, currencyCode) {
		this.ID = id;
		this.GUID = guid;
		this.DestinationID = destinationID;
		this.ownerInfo = ownerInfo;
		this.MinimumFlightItems = minFlightItems;
		this.MinimumHotelItems = minHotelItems;
		this.MinimumServiceItems = minServiceItems;
		this.MinimumCarItems = minCarItems;
		this.Items = [];
		this.StaticItems = [];
		this.TotalPrice = 0;
		this.Pricing = "";
		this.StartUrl = startURL;
		this.Type = type;
		
		if (currencyCode == null) {
			this.currencyCode = 'kr.';
		} else {
			this.currencyCode = currencyCode;
		}

		var c = $.cookieJar('ODIN-BOOKING-DATA', { cookiePrefix: '' });

		if (c != null) {
			$('#p_adult_count').val(c.get('adult_count'));
			$('#p_child_count').val(c.get('child_count'));
			$('#p_infant_count').val(c.get('infant_count'));
			this.CategoryID = c.get('package_category_id');
		}
		
		this.Adults = $('#p_adult_count').val();
		this.Children = $('#p_child_count').val();
		this.Infants = $('#p_infant_count').val();
		
		this.calculate();
	},
	calculate: function() {      
		this.Items = [];

		//$('#p_btn_continue').disabled = true;
		$('#p_btn_continue').attr( 'disabled', 'true' );
		$('#p_btn_continue').parent().addClass('disabled');
		$('#p_btn_calculate').attr( 'disabled', 'true' );
		$('#p_btn_calculate').parent().addClass('disabled');
		$('#price_loader').show();
		$('#p_error_msg').hide();

		_thisPD = this;
		$.timer(500, this.perform);
	},
	perform: function() {
		var flightItems = 0;
		var hotelItems = 0;
		var serviceItems = 0;
		var carItems = 0;
		var minimumItemsCheck = true;
	    _thisPD.Items = [];
		_thisPD.StaticItems = [];
   		var itemInternalIDs = "";
		var itemStaticIDs = "";
		var departureDateID = 0;
		var	departureDateCheck = false;
        		
		if (_thisPD.Type == 'Static') {
			departureDateID = $('#dd_id').val();
			if (departureDateID > 0) {
				departureDateCheck = true;
			}
			
		} else {
			departureDateCheck = true; 
		}                       

		$('span.cb input:checked').each(function(i, item) {		      
			var itemID = $(item).attr('itemid');
			var itemType =  $(item).attr('itemtype');			
			var inventoryType = $(item).attr('iteminventorytype');
			 
			if (inventoryType == 'Internal') {
				if ($('#packageItem_' + itemID + ':checked').length > 0 ) {
					_thisPD.Items[_thisPD.Items.length] = itemID;
					itemInternalIDs += itemID + '|';
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}
				}
			} else if (inventoryType == 'Static') {
			 
				if ($('#packageItem_'+itemID + ':checked').length > 0) {
					_thisPD.StaticItems[_thisPD.StaticItems.length] = itemID;
					itemStaticIDs += itemID + '|';
					                    
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}
				}
			}
		});
		
		if (flightItems < _thisPD.MinimumFlightItems) {		
			minimumItemsCheck = false;
		} else if (hotelItems < _thisPD.MinimumHotelItems) {			
			minimumItemsCheck = false;
		} else if (serviceItems < _thisPD.MinimumServiceItems) {
			minimumItemsCheck = false;
		} else if (carItems < _thisPD.MinimumCarItems) {
			minimumItemsCheck = false;
		}  
		
		_thisPD.Adults = $('#p_adult_count').val();
		_thisPD.Children = $('#p_child_count').val();
		_thisPD.Infants = $('#p_infant_count').val();
		
		if (minimumItemsCheck && departureDateCheck) {
		    var culture = "";
			if($('#pp_culture').length > 0) culture = $('#pp_culture').val(); 
			Odin.Modules.Support.OdinAPI.CheckPackageItemsAvailabilityAndPrice(_thisPD.ownerInfo, _thisPD.ID, _thisPD.Items, _thisPD.StaticItems, departureDateID, _thisPD.Adults, _thisPD.Children, _thisPD.Infants,culture, function(r) { 
				if (r.Success) {
					if (r.Results.Success) {
						_thisPD.TotalPrice = r.Results.TotalPrice;
						
						$('#p_total_price').html(addCommas(r.Results.TotalPrice));
						$('#p_total_price').show();
						$('.price').show();
						$('#p_btn_continue').removeAttr('disabled');
						$('#p_btn_continue').parent().removeClass('disabled');
						$('#message_box').removeClass('error').hide();
						
						_thisPD.Pricing = "";

						for( var i = 0; i < r.Results.AvailabilityItems.length; i++){
							_thisPD.Pricing += r.Results.AvailabilityItems[i].CalculatedPrice.Encrypted + '|';
						}						
					} else {
						$('#p_total_price').html('0');
						$('#message_box').html(ol_PackageDetails_ErrorPrefix + ' ' + r.ErrorMessage).addClass('error').show();
					}			
				} else {
				    $('.price').hide();
				    $('#p_total_price').hide();
					$('#p_total_price').html('0');
					$('#message_box').html(ol_PackageDetails_ErrorPrefix + ' ' + r.ErrorMessage).addClass('error').show();
				}
				$('#price_loader').hide();
				$('#p_btn_calculate').removeAttr('disabled');
				$('#p_btn_calculate').parent().removeClass('disabled');
			});
		} else {
			$('#p_total_price').html(" -- select hotel -- ");
			$('#price_loader').hide();
			$('#p_btn_calculate').removeAttr('disabled');
			$('#p_btn_calculate').parent().removeClass('disabled');
		}
	},
	close: function() {
		$('#message_box').hide();
	},	
	select: function() {
		var flightItems = 0;
		var hotelItems = 0;
		var serviceItems = 0;
		var carItems = 0;
		var minimumItemsCheck = true;
		_thisPD.Items = [];
		var itemInternalIDs = "";
		var itemStaticIDs = "";
		var departureDateID = 0;
		var	departureDateCheck = false;
        
        if (_thisPD.Type == 'Static') {
			departureDateID = $('#dd_id').val();
			if (departureDateID > 0) {
				departureDateCheck = true;
			}
		} else {
			departureDateCheck = true; 
		}
		
		$('span.cb input:checked').each(function(i, item) {		   
			var itemID =  $(item).attr('itemid');
			var itemType =  $(item).attr('itemtype');
			var inventoryType = $(item).attr('iteminventorytype');
			
			if (inventoryType == 'Internal') {
				if ($('#packageItem_'+itemID + ':checked').length > 0) {
					_thisPD.Items[_thisPD.Items.length] = itemID;
					itemInternalIDs += itemID + '|';
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}		
				}
			} else if (inventoryType == 'Static') {
				if ($('#packageItem_'+itemID + ':checked').length > 0) {
					_thisPD.StaticItems[_thisPD.StaticItems.length] = itemID;
					itemStaticIDs += itemID + '|';
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}		
				}							
			}	
		});  
				
		if (flightItems < _thisPD.MinimumFlightItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_flight.replace('--', _thisPD.MinimumFlightItems));
		} else if (hotelItems < _thisPD.MinimumHotelItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_hotel.replace('--', _thisPD.MinimumHotelItems));
		} else if (serviceItems < _thisPD.MinimumServiceItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_service.replace('--', _thisPD.MinimumServiceItems));
		} else if (carItems < _thisPD.MinimumCarItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_car.replace('--', _thisPD.MinimumCarItems));
		}

		if (minimumItemsCheck && departureDateCheck) {
			//SET COOKIE:
			var c = $.cookieJar('ODIN-BOOKING-DATA', { cookiePrefix: '' });
			c.remove();		
			c.set('urls', 'Package|Passengers|Payment|Receipt');
			c.set('owner_id', _thisPD.ownerInfo.split('|')[0]);
			c.set('search_type', 'Packages');
			c.set('flight_only', false);
			c.set('one_way', false);
		
   			c.set('set_package_guid', _thisPD.GUID);
			c.set('set_package_price',_thisPD.TotalPrice);
			c.set('set_package_item_pricings',_thisPD.Pricing);
			c.set('set_package_item_i_ids',itemInternalIDs);
			c.set('set_package_item_s_ids',itemStaticIDs);
			c.set('set_departure_date_id',departureDateID);

			c.set('adult_count', _thisPD.Adults);
			c.set('child_count', _thisPD.Children);
			c.set('infant_count', _thisPD.Infants);
			c.set('departure_date', '1999-12-31');
			c.set('arrival_date', '1999-12-31');
			c.set('arrival_destination_id', _thisPD.DestinationID);
			c.set('set_package_id', _thisPD.ID);
			c.set('package_id', _thisPD.GUID);
			c.set('package_category_id', _thisPD.CategoryID);
			top.window.location.href = _thisPD.StartUrl;
		}
	}
});


/*	PAYMENT PAGE:
	--------------------------------------------------------------------------------------------------------------------- */
Book = function() {
	this.init();
};
jQuery.extend(Book.prototype, {
	init: function() {
		$.fn.colorbox.init();
	},
	doBooking: function(ownerInfoString, formID) {
		if ($('#' + formID).valid()) {
			this.getGiftVoucherInfo();
			this.getCustomer();
			this.getCreditCardInfo();
			this.getPaymentDate();
			this.target = '';
            
			var ip = $('#ip_address').val();
			var userAgent = navigator.userAgent;
			var userComment = '';
			var totalPrice = $('#total_price').val();
			var currentURL = getCurrentPage();

			$.fn.colorbox({
				href: '#booking_loader_container',
				inline: true,
				initialWidth: 700,
				initialHeight: 440,
				width: 700,
				height: 440,
				overlayClose: false,
				open:true
			});
			$(document).bind('cbox_closed', function(){ $('#booking_error').hide(); $('#booking_loader_container').hide(); });

			$('#booking_loader_container').show();
			$('#booking_loader').show();
			$('#booking_error').hide();

			Odin.Modules.Support.OdinAPI.CreateBooking(ownerInfoString, this.paymentDate, this.customer, this.card, this.paymentType, this.giftVoucher, ip, userAgent, userComment, currentURL, function(r) {
				this.result = r;
				if (this.result.Success) {
					top.window.location.href = r.NextUrl;
				} else {
					handleBookingError(r.ErrorCode, r.ErrorMessage, r.PaymentResponses);
				}
			}, ajaxError);
		}
	},  
 	doBookingExternal: function (ownerInfoString, url, formID) {
    	var cb = $('.terms input')[0];

		if (!cb.checked) {
			alert(ol_PaymentTermsNotAgreed);
			return false;
		}

		if ($('#' + formID).valid()) {
			this.getGiftVoucherInfo();
			this.getCustomer();
			this.getPaymentDate();
			this.paymentType = 'OnePayment';
			this.card = new Zeus.Odin.DisillModules.Common.CreditCardInfo();
	
			var ip = $('#ip_address').val();
			var userAgent = navigator.userAgent;
			var userComment = '';
			var totalPrice = $('#total_price').val();
			var currentURL = getCurrentPage();
	
			$.fn.colorbox({
				href: '#booking_loader',
				inline: true,
				initialWidth: 700,
				initialHeight: 440,
				width: 700,
				height: 440,
				overlayClose: false,
				open:true
			});
			
			Odin.Modules.Support.OdinAPI.CreateBooking(ownerInfoString, this.paymentDate, this.customer, this.card, this.paymentType, this.giftVoucher, ip, userAgent, userComment, currentURL, function(r) {
				this.result = r;
				$.log(r);
				if (this.result.Success) {
					CreatePaymentCookie(r.BookingID, r.BookingIDWithPrefix, totalPrice)				
					top.window.location.href = url
				} else {
					handleBookingError(r.ErrorCode, r.ErrorMessage, r.PaymentResponses);
				}
			}, ajaxError);
		} else {
			alert('not valid');
		}
	},
	getCustomer: function() {
		this.customer = new Odin.Modules.Common.Customer();
		this.customer.FirstName = $('#customer_first_name').val();
		this.customer.LastName = $('#customer_last_name').val();
		this.customer.IdNumber = $('#customer_idnumber').val();
		this.customer.Address = $('#customer_address').val();
		this.customer.ZipCode = $('#customer_zipcode').val();
		this.customer.City = $('#customer_city').val();
		this.customer.Country = $('#customer_country').val();
		this.customer.Email = $('#customer_email').val();
		this.customer.PhoneHome = $('#customer_phone_home').val();
		this.customer.PhoneWork = $('#customer_phone_work').val();
		this.customer.PhoneMobile = $('#customer_phone_mobile').val();
	},
	getCreditCardInfo: function() {
		this.card = new Odin.Modules.Common.CreditCardInfo();
		this.paymentType = 'NotSelected';

		// GENERAL INFO:
		this.card.Number = $('#cc_number').val();
		this.card.ExpiresMonth = $('#cc_valid_month').val();
		this.card.ExpiresYear = $('#cc_valid_year').val();
		this.card.OwnerIdNumber = $('#cc_cardholder_idnumber').val();
		this.card.OwnerName = $('#cc_cardholder_name').val();
		this.card.CcvNumber = $('#cc_ccv_code').val();
		this.card.NumberOfMonths = 0;
		
		if($('#payment_options').val() == 'simple') {
			this.paymentType = 'OnePayment';
			this.card.Type = $('#cc_type').val();
		} else {
			// CARD TYPE:
			if ($('#paytype_mc_one:checked').length > 0 || $('#paytype_mc_split:checked').length > 0 || $('#paytype_mc_contract:checked').length > 0) {
				this.card.Type = 'MasterCard';
			} else if ($('#paytype_visa_one:checked').length > 0 || $('#paytype_visa_split:checked').length > 0|| $('#paytype_visa_contract:checked').length > 0 || $('#paytype_visa_four_even:checked').length > 0) {
				this.card.Type = 'VISA';
			}
	
			if ($('#paytype_mc_one:checked').length > 0 || $('#paytype_visa_one:checked').length > 0) {
				this.paymentType = 'OnePayment';
			} else if ($('#paytype_mc_contract:checked').length > 0 || $('#paytype_visa_contract:checked').length > 0) {			
				this.paymentType = 'OneContract';
				
				if (this.card.Type == 'VISA') {
					this.card.NumberOfMonths = $('#visa_contracts_months').val();
				} else if (this.card.Type == 'MasterCard') {			
					this.card.NumberOfMonths = $('#mc_contracts_months').val();
				}
				
			} else if ($('#paytype_mc_split:checked').length > 0 || $('#paytype_visa_split:checked').length > 0) {        		
				this.paymentType = 'SplitContract';
				this.card.NumberOfMonths = 3;
			} else if ($('#paytype_visa_four_even:checked').length > 0) {
				this.paymentType = 'FourEvenPayments';
				this.card.NumberOfMonths = 4;
			}	
		}
	},
	getGiftVoucherInfo: function() {
		this.giftVoucher = giftVoucherInfo;
	},
	getPaymentDate: function() {
		this.paymentDate = '2000-01-01';  
		if (this.paymentType == 'OneContract') {
			if (this.card.Type == 'MasterCard') {
				this.paymentDate = $('#date_mc_contract').val();
			} else if (this.card.Type == 'VISA') {
				this.paymentDate = $('#date_visa_contract').val();
			}
		} else if (this.paymentType == 'SplitContract') {
			if (this.card.Type == 'MasterCard') {
				this.paymentDate = $('#date_mc_split').val();
			} else if (this.card.Type == 'VISA') {
				this.paymentDate = $('#date_visa_split').val();
			}
		}
	},
	copyPassengerInfo: function() {
		if ($('#passenger_id').val().length > 0) {
			var pi = $('#passenger_id').val().split(';');
			$('#customer_first_name').val(pi[0]);
			$('#customer_last_name').val(pi[1]);
			$('#customer_idnumber').val(pi[2]);
			$('#customer_address').get(0).focus();
			
		} else {
			$('#customer_first_name').val('');
			$('#customer_last_name').val('');
			$('#customer_idnumber').val('');
			$('#customer_first_name').get(0).focus();
		}
	}
});

function CreatePaymentCookie(bookingID, bookingPrefix, amount) {
	var c = $.cookieJar('REDUNICRE-PAYMENT-DATA', {
		expires: 1,
		path: '/',
		cookiePrefix: ''
	});
	c.set('BookingIDWithPrefix', bookingPrefix)
    c.set('BookingID', bookingID);
    c.set('Amount',amount)        
}

/*	----------< CHECK MULTIPLE FLIGHTS >---------------------------------------------------------------------------------- */
function SelectFlightsAndMove(ownerInfo) {
	var departureFlightID = 0;
	var arrivalFlightID = 0;

	$('input.rad_dep').each(function(i, item) {
		if ($(item).attr("checked")) {
			departureFlightID = $(item).val();
		}
	});
	
	$('input.rad_arr').each(function(i,item) {
		if ($(item).attr("checked")) {
			arrivalFlightID = $(item).val();
		}
	});
	
	Odin.Modules.Support.OdinAPI.SelectFlights(ownerInfo, departureFlightID, arrivalFlightID, function(r) {
		if (r.Success) {
			top.window.location.href = r.NextUrl;
		} else {
			alert('Error:\n' + r.ErrorMessage);
		}
	}, Error);
}
/*	----------< SAVE HOTEL >---------------------------------------------------------------------------------------------- */
function SelectHotelAndRoom(hotelID, roomTypeID, mealPlanID, price, mealPlanPrice, calculatedPrices, mealPlanCalculatedPrices) {
	Odin.Modules.Support.OdinAPI.SelectHotel(hotelID, roomTypeID, mealPlanID, price, mealPlanPrice, calculatedPrices, mealPlanCalculatedPrices, getCurrentPage(), function(r) {
		if (r.Success) {
			top.window.location.href = r.NextUrl;
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}
/*	----------< CARS >---------------------------------------------------------------------------------------------------- */
function SaveCarInfo(typeID, from, to, price) {
	Odin.Modules.Support.OdinAPI.SaveCarInfo(typeID, from, to, price, getCurrentPage(), function(r) {
		if (r.Success) {
			top.window.location.href = r.NextUrl;
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}
/*	----------< PASSENGER INFO >------------------------------------------------------------------------------------------ */
function validatePassengerForm() {
	var ret = true;

	$('input.el-req').each(function() {
		$(this).bind('keyup blur', inputValidator);
		if ($(this).val().length <= 1) {
			$(this).addClass('invalid');
			if ($('#' + this.id + ' + span').length == 0) {
				$('<span>' + $(this).attr('error') + '</span>').addClass('invalid').appendTo(this.parentNode);
			}

			if (ret) {
				ret = false;
			}
		}
	});
	
	$('input.int').each(function() {
		$(this).bind('keyup blur', inputValidator);
		if (!($(this).val()).match(/^[-+]?\d+$/)) {
			$(this).addClass('invalid');
			if ($('#' + this.id + ' + span').length == 0) {
				$('<span>' + $(this).attr('error') + '</span>').addClass('invalid').appendTo(this.parentNode);
			}

			if (ret) {
				ret = false;
			}
		}		
	});
	
	return ret;
}
var inputValidator = function validateInput(ev) {
	$(this).removeClass('invalid');

	if ($(this).val().length <= 1) {
		$(this).addClass('invalid');
		if ($('#' + this.id + ' + span').length == 0) {
			$('<span>' + $(this).attr('error') + '</span>').addClass('invalid').appendTo(this.parentNode);
		}
	} else {
		$('#' + this.id + ' + span').remove();
	}
};
function AreTermsAgreed(Required) {
	if ( Required && $('#terms:checked').length === 0) {
		alert(ol_PassengerTerms);
		return false;
	} else {
		return true;
	}
}
function GetPassenger(type, index, arr) {
	var passenger = new Odin.Modules.Common.Passenger();

	passenger.FirstName = $('#passenger-' + type + '-' + index + '-firstname').val();
	passenger.LastName = $('#passenger-' + type + '-' + index + '-lastname').val();
	passenger.IdNumber = $('#passenger-' + type + '-' + index + '-idnumber').val();
	passenger.Type = type;
	passenger.Gender = $('#passenger-' + type + '-' + index + '-gender').val();
	arr[arr.length] = passenger;
}
function SavePassengerInfo(ReqAgreeTerms) {
	if( ReqAgreeTerms == null )
		ReqAgreeTerms = true;

	if (validatePassengerForm() && AreTermsAgreed(ReqAgreeTerms) ) {
		var adults = parseInt($('#count_adt').val(),10);
		var children = parseInt($('#count_chd').val(),10);
		var infants = parseInt($('#count_inf').val(),10);
		var total = adults + children + infants;
		var passengers = [];

		if (total > 0) {
			for (var i = 1; i <= adults; i++) {
				GetPassenger('Adult', i, passengers);
			}
			for (var i = 1; i <= children; i++) {
				GetPassenger('Child', i, passengers);
			}
			for (var i = 1; i <= infants; i++) {
				GetPassenger('Infant', i, passengers);
			}
		}

		// SAVE PASSENGERS:
		Odin.Modules.Support.OdinAPI.SavePassengers(passengers, getCurrentPage(), function(r) {
			if (r.Success) {			
		    	top.window.location.href = 'https://' + location.host + r.NextUrl;
			} else {
				alert(r.ErrorMessage);
			}
		}, Error);
 	}
}

/*	----------< SERVICES >------------------------------------------------------------------------------------------------ */
ServiceSelectionModule = function(totalPrice, passengerCount, itemCount) {
  this.init(totalPrice, passengerCount, itemCount);
};
jQuery.extend(ServiceSelectionModule.prototype, {
	init: function(totalPrice, passengerCount, itemCount) {
		this.TotalPrice = Math.round(totalPrice);
		this.ServicePrice = parseInt(0);
		this.Selections = [];
		this.SelectionIDs = [];
	},
	add: function(item, adding) {
		if ($.inArray(item.IdNumber,this.SelectionIDs) > -1) {
			ind = this.SelectionIDs.indexOf(item.IdNumber);
			this.Selections.splice(ind, 1);
			this.SelectionIDs = $.grep(this.Selections, function(val) {return val != item.IdNumber; });
			this.ServicePrice = this.ServicePrice - parseInt(item.Price);
		} else {
			this.Selections.push(item);
			this.SelectionIDs.push(item.IdNumber);
			this.ServicePrice = this.ServicePrice + parseInt(item.Price);
		}

		var totalPrice = this.TotalPrice + Math.round(this.ServicePrice);
		$('#TotalPrice').html(addCommas(totalPrice));
	},
	save: function() {
		var selections = [];
	 
		jQuery.each(this.Selections,function(i,item) {
			var serviceSelection = new Zeus.Odin.DisillModules.API.ServiceSelection();
			
			serviceSelection.Index = item.IdNumber;
			serviceSelection.ServiceID = item.ServiceID;
			serviceSelection.ServiceItemID = item.ServiceItemID;
			serviceSelection.ServicePeriodID = item.ServicePeriodID;
			serviceSelection.Price = item.Price;
			serviceSelection.Pricing =  item.Pricing;
			
			selections[selections.length] = serviceSelection;
		});
		
		Odin.Modules.Support.OdinAPI.SaveServiceInfo(selections, getCurrentPage(), function(r) {
			if (r.Success) {
				top.window.location.href = r.NextUrl;
			} else {
				alert(r.ErrorMessage);
			}
		}, Error);
	},
	addGroup: function(item, adding) {
		this.Selections = [];
		this.Selections.push(item);		
		
		$('#saveBtn').show();
	},
	saveGroup: function(pickupHotelID, pickupRoomNumber, pickupTime) {	 
		var item = this.Selections[0];

		if (!item.PriceChild) {
			item.PriceChild = 0;
		}
		if (!item.PriceInfant) {
			item.PriceInfant = 0;
		}
		if (pickupHotelID == -1) {
			item.PickupPrice = 0;
		}

		Odin.Modules.Support.OdinAPI.SaveServiceGroupInfo(item.ServiceDateID, item.ServiceID, item.ServiceCategoryID, item.PriceAdult, item.PriceChild, item.PriceInfant, getCurrentPage(), pickupHotelID, pickupRoomNumber, item.PickupPrice, pickupTime, item.PricingAdult, item.PricingChild, item.PricingInfant, function(r) {
			if (r.Success) {
				top.window.location.href = r.NextUrl;
			} else {
				alert(r.ErrorMessage);
			}
		}, ajaxError);		
	} 	
});


ServiceSelectionItem = function(idNumber, serviceID, serviceItemID, servicePeriodID, price, pricing) {
	this.init(idNumber, serviceID, serviceItemID, servicePeriodID, price, pricing);
};
jQuery.extend(ServiceSelectionItem.prototype, {
	init: function(idNumber, serviceID, serviceItemID, servicePeriodID, price, pricing) {
		this.IdNumber = idNumber;
		this.ServiceID = serviceID;
		this.ServiceItemID = serviceItemID;
		this.ServicePeriodID = servicePeriodID;
		this.Price = price;
		this.Pricing = pricing;
	}
});


ServiceSelectionGroup = function(serviceDateID, serviceID, serviceCategoryID, priceAdult, priceChild, priceInfant, allowPickup, pickupPrice, destinationID, pricingAdult, pricingChild, pricingInfant) {
	this.init(serviceDateID, serviceID, serviceCategoryID, priceAdult, priceChild, priceInfant, allowPickup, pickupPrice, destinationID, pricingAdult, pricingChild, pricingInfant);
};
jQuery.extend(ServiceSelectionGroup.prototype, {
	init: function(serviceDateID, serviceID, serviceCategoryID, priceAdult, priceChild, priceInfant, allowPickup, pickupPrice, destinationID, pricingAdult, pricingChild, pricingInfant) {
		this.ServiceDateID = serviceDateID;
		this.ServiceID = serviceID;
		this.ServiceCategoryID = serviceCategoryID;
		this.PriceAdult = priceAdult;
		this.PriceChild = priceChild;
		this.PriceInfant = priceInfant;                                                                                                       
		this.AllowPickup = allowPickup;
		this.PickupPrice = pickupPrice;
		this.DestinationID = destinationID;
		this.PricingAdult = pricingAdult;
		this.PricingChild = pricingChild;
		this.PricingInfant = pricingInfant;
	}
});

/*	----------< PAYMENTS >------------------------------------------------------------------------------------------------ */
function SwitchPaymentType(type) {
	$('#mc_months').hide();
	$('#visa_months').hide();
	
	if (type == 'mc_contract') {
		$('#mc_months').show();
	} else if (type == 'visa_contract') {
		$('#visa_months').show();
	}
}

function ShowCalculations(type) {
	var url = '';
	var totalAmount = parseInt($('#total_price').val()) - parseInt($('#gift_voucher_amount').val());
	var monthCount = null;

	if (type == 'mc') {
		monthCount = $('#mc_contracts_months').val();

		if (monthCount == 0) {
			alert('Veldu fjÃ¶lda mÃ¡naÃ°a');
			return;
		}

		url = '/bokun/utreikningar/mastercard/' + monthCount + '/' + totalAmount + '/0/';
	}
	
	if (type == 'visa') {
		monthCount = $('#visa_contracts_months').val();
		
		if (monthCount == 0) {
			alert('Veldu fjÃ¶lda mÃ¡naÃ°a.');
			return;
		}

		url = '/bokun/utreikningar/visa/' + monthCount + '/' + totalAmount + '/0/false/';
	}
	
	if (url.length > 0 && monthCount > 0 && totalAmount > 0) {
		window.open(url);
	}
}

var giftVoucherInfo = null;

function CheckGiftVoucher(ownerInfo) {
	Odin.Modules.Support.OdinAPI.CheckGiftVoucher(ownerInfo, $('#giftvoucher_code').val(), function(r) {
		if (r.Success) {
			giftVoucherInfo = new Zeus.Odin.DisillModules.Common.GiftVoucherInfo();
			giftVoucherInfo.Amount = r.Availability.Amount;
			giftVoucherInfo.ID = r.Availability.CodeID;
			giftVoucherInfo.Type = r.GiftVoucherType;
			giftVoucherInfo.Code = $('#giftvoucher_code').val();
			
			var oldTotalAmount = parseInt($('#total_price').val());
			var newTotalAmount = (oldTotalAmount - r.Availability.Amount);
			
			alert('GjafabrÃ©f var dregiÃ° frÃ¡ heildarverÃ°i.\nVerÃ° fyrir: ' + addCommas(oldTotalAmount) + '\nUpphÃ¦Ã° gjafabrÃ©fs: ' + addCommas(r.Availability.Amount) + '\nVerÃ° nÃº: ' + addCommas(newTotalAmount));
			
			$('.price').html(addCommas(newTotalAmount));
		} else {
			alert('GjafabrÃ©f meÃ° nÃºmerinu sem Ã¾Ãº slÃ³st inn fannst ekki.');
		}
	}, Error);
}
/*	----------< MY PAGES >------------------------------------------------------------------------------------------------ */
function SendVoucherViaEmail (customerID, bookingID) {
	$('#sendVoucher_loader').show();
	Odin.Modules.Support.OdinAPI.SendVoucher(customerID, bookingID, function(r) {
		$('#sendVoucher_loader').hide();
		if (r.Success) {
		    alert('StaÃ°festingin var send');
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}
function SendInvoiceViaEmail (customerID, bookingID) {
	$('#sendInvoice_loader').show();
	Odin.Modules.Support.OdinAPI.SendInvoice(customerID, bookingID, function(r) {
		$('#sendInvoice_loader').hide();
		if (r.Success) {
		    alert('Reikningurinn var sendur');
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}

/*	--< HOTEL PRICE CHECK >------------------------------------------------------ */
function GetHotelPriceQuote(ownerInfo, hotelID) {
	var from = $('#cp_datepicker_from').val();
	var to = $('#cp_datepicker_to').val();
	var adults = $('#cp_adult_count').val();
	var children = $('#cp_child_count').val();
	var infants = $('#cp_infant_count').val();
	
	$('.price-quote .loader').show();
	$('.price-quote #results').empty();
	
	tmr = $.timer(1000, function() {
		Odin.Modules.Support.OdinAPI.HotelPriceQuote(ownerInfo, hotelID, from, to, adults, children, infants, 1, function(r) {
		    var html = '';
		    if (r.length > 0) {
				$.each(r, function() {
					if (this.MealPlan != null) {
					    html += '<div class="room">' +
								'<span class="name">' + this.RoomName + ' - ' + this.MealPlan.Name + '</span>' +
								'<span class="price pr-person">' + ol_PriceQuote_PricePrPerson + ':<br /><span class="blue">' + $.numberFormatThing(this.PricePrPerson, 'e') + ' EUR</span></span>' +
								'<span class="price total">' + ol_PriceQuote_Price + ':<br /><span class="blue">' + $.numberFormatThing(this.Price, 'e') + ' EUR</span></span>' +
							    '<span class="book-now"><a class="book" href="#book-room" onclick="SelectRoomFromPriceQuote(\'' + ownerInfo + '\', ' + this.HotelID + ', ' + this.ID + ', ' + this.MealPlan.ID +  ' , ' + this.Price + ',' + this.MealPlan.Price + ');return false;">' + ol_PriceQuote_BookNow + '</a></span>' +
							'</div>';					
					}
					else {			
					    html += '<div class="room">' +
								'<span class="name">' + this.RoomName + '</span>' +
								'<span class="price pr-person">' + ol_PriceQuote_PricePrPerson + ':<br /><span class="blue">' + $.numberFormatThing(this.PricePrPerson, 'e') + ' EUR</span></span>' +
								'<span class="price total">' + ol_PriceQuote_Price + ':<br /><span class="blue">' + $.numberFormatThing(this.Price, 'e') + ' EUR</span></span>' +
							    '<span class="book-now"><a class="book" href="#book-room" onclick="SelectRoomFromPriceQuote(\'' + ownerInfo + '\', ' + this.HotelID + ', ' + this.ID + ',0, ' + this.Price + ',0);return false;">' + ol_PriceQuote_BookNow + '</a></span>' +
							'</div>';
						}
				});
			} else {
				html = '<div class="error">' + ol_PriceQuote_NoResult + '</div>';
			}

			$('#results').html(html);
			$('.price-quote .loader').hide();
		}, Error);
	});
}

function SelectRoomFromPriceQuote(ownerInfo, hotelID, roomTypeID, mealPlanID, price, mealPlanPrice) {
	var c = $.cookieJar('ODIN-BOOKING-DATA', {
		expires: 7,
		path: '/',
		cookiePrefix: ''
	});

	// DEFAULT COOKIE VALUES:
	c.set('urls', 'Passengers|Payment|Receipt');
	c.set('owner_id', ownerInfo.split('|')[0]);
	c.set('adult_count', $('#cp_adult_count').val());
	c.set('child_count', $('#cp_child_count').val());
	c.set('infant_count', $('#cp_infant_count').val());
	c.set('search_type', 'Standard');
	c.set('package_id', '0');

	c.set('departure_date', $('#cp_datepicker_from').val());
	c.set('arrival_date', $('#cp_datepicker_to').val());
	c.set('arrival_destination_id', $('#qs_arriving_destination_id').val());
	c.set('departure_destination_id', 0);
	c.set('service_category_id', 0);

	c.set('departure_flight_id', 0);
	c.set('arrival_flight_id', '0');
	c.set('flight_only', false);
	c.set('one_way', false);
	
	// SPECIAL HOTEL SELECTION VALUES:
	c.set('set_hotel_id', hotelID);
	c.set('set_roomtype_id', roomTypeID);
	c.set('set_mealplan_id', mealPlanID);
	c.set('set_hotel_price', price);
	c.set('set_mealplan_price', mealPlanPrice);

	// SEND TO START PAGE:
	top.window.location.href = '/book/start/';
}

// ---------------------------------------------------------------------------------------------------------------
