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);
}

var ol_BookingError_Code = "Villa við framkvæmd greiðslu";

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 + ')';
	}
	//$('#cboxLoadedContent').html( $('#booking_error').html().replace('%%MSG%%', errMsg) );
	$('#booking_loading').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="">hleð dagsetningum ...</option>');		
		Zeus.Odin.DisillModules.API.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="">hleð dagsetningum ...</option>');
		Zeus.Odin.DisillModules.API.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.urls = '';
		this.searchType = 'Departures';
		this.freezeElements = false;
		this.iframeSearch = 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'));
			$('#qs_datepicker_from').val(c.get('departure_date'));
			$('#qs_datepicker_to').val(c.get('arrival_date'));
			this.urls = c.get('urls');
			this.searchType = c.get('search_type');
		}
	},
	hideAll: function() {
		$('.qs-module').addClass('hidden');
	},
	showItem: function(item) {
		$('#' + item).removeClass('hidden');	
	},
	setUrls: function(inUrls) {
		this.urls = inUrls;
	},
	loadSelectedDestinations: function() {
	    if (!this.freezeElements) {
			var c = $.cookieJar('ODIN-BOOKING-DATA', {
				path: '/',
				expires: 7,
				cookiePrefix: ''
			});
			if (c.toObject()) {
				if ($('#qs_departure_destination_id')[0].selectedIndex > 0 && $('#qs_arriving_destination_id')[0].selectedIndex > 0) {
	        		loadDates();
				}
			}
		}
	},
	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="">-- veldu dags --</option>');
			jQuery.each(this.departures,function(i,item) {
				var text = item.FormattedDate;
				
				if (item.AvailableSeatCount < 1) {
					text += ' - UPPSELT';
				} else if (item.AvailableSeatCount >= 1 && item.AvailableSeatCount < 7) {
					text += ' - ' + item.AvailableSeatCount + ' sæti eftir';
				}
                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="">-- veldu dags --</option>');

			jQuery.each(this.arrivals,function(i,item) {
				var text = item.FormattedDate;
				
				if (item.AvailableSeatCount < 1) {
					text += ' - UPPSELT';
				} else if (item.AvailableSeatCount >= 1 && item.AvailableSeatCount < 7) {
					text += ' - ' + item.AvailableSeatCount + ' sæti eftir';
				}
				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('Enginn flug', '');
		}
	},
	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) {
			Zeus.Odin.DisillModules.API.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_QuickSearch_PackageTripSelect + ' --</option>');
					jQuery.each(r.Packages,function(i,item) {
						selectList.append('<option value="'+ item.GUID + '">' + item.Name + '</option>');  
						
					});

					
				} else {			
					selectList.disabled = true;
					selectList.append('<option value="">' + ol_QuickSearch_PackageTripSelectNoTrips +'</option>');
					//alert('Enginn ferð fannst í þessum flokki\nVeldu aðra tegund.');
				}
			}, Error);
		}
	},
	search: function(url) {     
		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('Þú verður að velja brottfararstað.');
	  			return;
	  		}
	  		// CHECK ON IF BOTH FLIGHTS ARE SELECTED IN FLIGHT AND HOTEL SEARCH:
	  		if ($('#qs_arriving_destination_id').val().length === 0) {
	  			alert('Þú verður að velja áfangastað.');
	  			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('Þú verður að velja bæði dagsetningu brottfarar og heimkomu.');
	  			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('Þú verður að velja dagsetningu brottfarar.');
	  			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('Ertu viss um að þú viljir velja flug aðeins aðra leiðina?')) {
	  				return;
	  			}
	  		}
	  		// CHECK IF THERE IS ENOUGH SEATS ON FLIGHT:
	  		if ( this.currentDateFrom != null) {
	  			if (this.currentDateFrom.split(':')[2] < 1) {
	  				alert('Flugið sem valið er á útleið er uppselt.');
	  				return;
	  			} else if ((parseInt(this.currentDateFrom.split(':')[2]) - (parseInt($('#qs_adult_count').val()) + parseInt($('#qs_child_count').val()))) < 0 ) {
	  				alert('Ekki eru til næg flugsæti fyrir alla farþega');
	  				return;			
	  			}
	  		}
	  		// CHECK IF THERE IS ENOUGH SEATS ON FLIGHT:
	  		if( this.currentDateTo != null ) {
	  			if (this.currentDateTo.split(':')[2] < 1) {
	  				alert('Flugið sem valið er á heimleið er uppselt.');
	  				return;
	  			} else if ((parseInt(this.currentDateTo.split(':')[2]) - (parseInt($('#qs_adult_count').val()) + parseInt($('#qs_child_count').val()))) < 0 ) {
	  				alert('Ekki eru til næg flugsæti fyrir alla farþega.');
	  				return;			
	  			}
	  		}
	  	} else if (this.searchType == 'Packages') {
	  		// CHECK PACKAGE CATEGORY SELECTION:
	  		if( $('#qs_packagecategory_id').get(0).selectedIndex == 0 ) {
	  			alert(ol_QuickSearch_PackageCategoryValidation);
	  			return;
	  		}
	  		// CHECK PACKAGE SELECTION:
	  		if ( $('#qs_package_id').get(0).selectedIndex == 0 ) {
	  			alert(ol_QuickSearch_PackageSelectionValidation);
	  			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_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 == 'Service') {
			
			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.DestinationID);
			c.set('flight_only', 'false');
			c.set('service_category_id', this.serviceCategoryID);
				
		} 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_id', $('#qs_package_id').val());
		}
		if (!this.iframeSearch) {
			top.window.location.href = url;
		} else {
			top.location.href = url;
		} 
	}
});


/*	PACKAGE PAGE:
--------------------------------------------------------------------------------------------------------------------- */
var _thisPD = null;
PackageDetails = function(id, guid, type, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL) {
	this.init(id, guid, type, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL);
};
jQuery.extend( PackageDetails.prototype, {
	init: function(id, guid, type, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems, startURL) {
		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.StartUrl = startURL;
		this.Type = type;	

		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.Adults = $('#p_adult_count').val();
		this.Children = $('#p_child_count').val();
		this.Infants = $('#p_infant_count').val();
		
		this.calculate();
	},
	calculate: function() {      
		this.Items = [];
		this.StaticItems = [];

		//$('#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;
		var departureDateID = 0;
		var	departureDateCheck = false; 
	    _thisPD.Items = [];
	    _thisPD.StaticItems = [];
	    
	    if (_thisPD.Type == 'Static') {
			departureDateID = $('#dd_id').val();
			if (departureDateID > 0) {
				departureDateCheck = true;
			}
		} else {
			departureDateCheck = true; 
		}			
	    
		$('span.cbclass').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;
					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;
					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) {
			Zeus.Odin.DisillModules.API.OdinAPI.CheckPackageItemsAvailabilityAndPrice(_thisPD.ownerInfo, _thisPD.ID, _thisPD.Items, _thisPD.StaticItems, departureDateID, _thisPD.Adults, _thisPD.Children, _thisPD.Infants, function(r) { 
				if (r.Success) {
					if (r.Results.Success) {
						_thisPD.TotalPrice = r.Results.TotalPrice;
						$('#p_total_price').html( addCommas(r.Results.TotalPrice) );
						$('#p_btn_continue').removeAttr('disabled');
						$('#p_btn_continue').parent().removeClass('disabled');
					} else {
						
						$('#p_total_price').html('0');
						$('#p_error_msg_holder').html(r.ErrorMessage);
						$('#p_error_msg').show();
					}			
				} else {
					$('#p_total_price').html('0');
					$('#p_error_msg_holder').html(r.ErrorMessage);
					$('#p_error_msg').show();
				}
				$('#price_loader').hide();
				$('#p_btn_calculate').removeAttr('disabled');
				$('#p_btn_calculate').parent().removeClass('disabled');
			});
		} else {
			$('#p_total_price').html(" -- " + ol_PackageDetails_SelectHotelOrServices + " -- ");
			$('#price_loader').hide();
			$('#p_btn_calculate').removeAttr('disabled');
			$('#p_btn_calculate').parent().removeClass('disabled');
		}
	},
	close: function() {
		$('#p_error_msg').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;
		
	    if (_thisPD.Type == 'Static') {
			departureDateID = $('#dd_id').val();
			if (departureDateID > 0) {
				departureDateCheck = true;
			}
		} else {
			departureDateCheck = true; 
		}			
		
		$('span.cbclass').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('Villa, velja þarf minnst ' + _thisPD.MinimumFlightItems + ' flugleggi.');
		} else if (hotelItems < _thisPD.MinimumHotelItems) {
			minimumItemsCheck = false;
			alert('Villa, velja þarf minnst ' + _thisPD.MinimumHotelItems + ' hótel.');
		} else if (serviceItems < _thisPD.MinimumServiceItems) {
			minimumItemsCheck = false;
			if (parseInt(_thisPD.MinimumServiceItems) > 1) {
				alert('Villa, velja þarf minnst ' + _thisPD.MinimumServiceItems + ' þjónustur.');
			} else {
				alert('Villa, velja þarf minnst ' + _thisPD.MinimumServiceItems + ' þjónustu.');
			}
		} else if (carItems < _thisPD.MinimumCarItems) {
			minimumItemsCheck = false;
			if (parseInt(_thisPD.MinimumCarItems) > 1) {
				alert('Villa, velja þarf minnst ' + _thisPD.MinimumCarItems + ' bílaleigubíla.');
			} else {
				alert('Villa, velja þarf minnst ' + _thisPD.MinimumCarItems + ' bílaleigubíl.');
			}
		}
		if (minimumItemsCheck) {

			//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_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);
			
			top.window.location.href = _thisPD.StartUrl;
		}
	}
});


/*	PAYMENT PAGE:
	--------------------------------------------------------------------------------------------------------------------- */
Book = function() {
	this.init();
};
jQuery.extend(Book.prototype, {
	init: function() {
		$.fn.colorbox.init();
	},
	doBooking: function(ownerInfoString) {
    	if ($("#OdinFormPage").valid()) {
			this.getGiftVoucherInfo();
			this.getCustomer();
			this.getCreditCardInfo();
			this.getPaymentDate();
			this.target = '';
            
			var ip = $('#ip_address').val();
			var userAgent = navigator.userAgent;
			$.fn.colorbox({
				href: '#booking_loader',
				inline: true,
				initialWidth: 700,
				initialHeight: 440,
				width: 700,
				height: 440,
				overlayClose: false,
				open:true
			});
			$('#booking_loading').show();
			$('#booking_error').hide();
			Zeus.Odin.DisillModules.API.OdinAPI.CreateBooking(ownerInfoString, this.paymentDate, this.customer, this.card, this.paymentType, this.giftVoucher, ip, userAgent,'', getCurrentPage(), function(r) {
				this.result = r;
				if (this.result.Success) {
					top.window.location.href = r.NextUrl;
				} else {
					handleBookingError(r.ErrorCode, r.ErrorMessage, r.PaymentResponses);
				}
			}, ajaxError);
		}
	},
	getCustomer: function() {
		this.customer = new Zeus.Odin.DisillModules.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 Zeus.Odin.DisillModules.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();
		}
	}
});
  /*	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();
		}
	});
	
	Zeus.Odin.DisillModules.API.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) {
	Zeus.Odin.DisillModules.API.OdinAPI.SelectHotel(hotelID, roomTypeID, mealPlanID, price, mealPlanPrice, getCurrentPage(), function(r) {
		if (r.Success) {
			top.window.location.href = r.NextUrl;
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}

  /*	CARS:
--------------------------------------------------------------------------------------------------------------------- */
function SaveCarInfo(supplierID, typeID, periodID, price) {
	Zeus.Odin.DisillModules.API.OdinAPI.SaveCarInfo(supplierID, typeID, periodID, 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('Vinsamlegast samþykktu skilmálana til að halda áfram');
		return false;
	} else {
		return true;
	}
}


function GetPassenger(type, index, arr) {
	var passenger = new Zeus.Odin.DisillModules.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:
		Zeus.Odin.DisillModules.API.OdinAPI.SavePassengers(passengers, getCurrentPage(), function(r) {
			if (r.Success) {			
		    	top.window.location.href = r.NextUrl;
			} else {
				alert(r.ErrorMessage);
			}
		}, Error);
 	}
}

/*	SELECT 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 = [];
	},
	add: function(item, adding) {
		var stringItem = item.IdNumber + ',' + item.ServiceID + ',' + item.ServiceItemID + ',' + item.ServicePeriodID + ',' + item.Price;

		if ($.inArray(stringItem,this.Selections) > -1) {
			this.Selections = $.grep(this.Selections, function(val) {return val != stringItem; });
			this.ServicePrice = this.ServicePrice - parseInt(item.Price);
		} else {
			this.Selections.push(stringItem);
			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();
			var arr = item.split(',');
			
			serviceSelection.Index = arr[0];
			serviceSelection.ServiceID = arr[1];
			serviceSelection.ServiceItemID = arr[2];
			serviceSelection.ServicePeriodID = arr[3];
			serviceSelection.Price = arr[4];
			
			selections[selections.length] = serviceSelection;
		});
		
		Zeus.Odin.DisillModules.API.OdinAPI.SaveServiceInfo(selections, getCurrentPage(), function(r) {
			if (r.Success) {
				if (document.location.protocol == "http:") {
					var url = window.location.href.replace('http://', '');
					url = url.substring(0, url.indexOf('/'));
					top.window.location.href = 'https://' + url + r.NextUrl;
				} else {
					top.window.location.href = r.NextUrl;
				}
			} else {
				alert(r.ErrorMessage);
			}
		}, Error);
	}
});

ServiceSelectionItem = function(idNumber, serviceID, serviceItemID, servicePeriodID, price) {
	this.init(idNumber, serviceID, serviceItemID, servicePeriodID, price);
};
jQuery.extend(ServiceSelectionItem.prototype, {
	init: function(idNumber, serviceID, serviceItemID, servicePeriodID, price) {
		this.IdNumber = idNumber;
		this.ServiceID = serviceID;
		this.ServiceItemID = serviceItemID;
		this.ServicePeriodID = servicePeriodID;
		this.Price = price;
	}
});



/*	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) {
	Zeus.Odin.DisillModules.API.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);
}


/*	MYPAGES:
	--------------------------------------------------------------------------------------------------------------------- */
function SendVoucherViaEmail (customerID, bookingID) {
	$('#sendVoucher_loader').show();
	Zeus.Odin.DisillModules.API.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();
	Zeus.Odin.DisillModules.API.OdinAPI.SendInvoice(customerID, bookingID, function(r) {
		$('#sendInvoice_loader').hide();
		if (r.Success) {
		    alert('Reikningurinn var sendur');
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}

function SendAmadeusTicketsViaEmail (customerID, bookingID) {
	$('#sendAmadeus_loader').show();
	Zeus.Odin.DisillModules.API.OdinAPI.SendAmadeusTickets(customerID, bookingID, function(r) {
		$('#sendAmadeus_loader').hide();
		if (r.Success) {
		    alert('Amadeus miðarnir voru sendir í tölvupósti');
		} else {
			alert(r.ErrorMessage);
		}
	}, Error);
}

