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 + ')';
	}

	$('#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="">' + ol_LoadingDates + '</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="">' + ol_LoadingDates + '</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('/'));
    }
    
    if(typeof String.prototype.trim !== 'function') { 
        String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, '');} 
    }
    
    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.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');
			
			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').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').length > 0 && $('#qs_departure_destination_id')[0].selectedIndex > 0 && $('#qs_arriving_destination_id').length > 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="">-- ' + 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) {
			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_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, serviceCategoryID, destinationID) {  
    
        if (destinationID != null) {
            this.DestinationID = destinationID;
        }
        
        if (serviceCategoryID != null) {
            this.serviceCategoryID = serviceCategoryID; 
        }            
		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;
	  		}
		} else if (this.searchType == 'SingleService') {
            var from = $('#qs_datepicker_from_' + selectedID).val();
            var to = $('#qs_datepicker_to_' + selectedID).val();    	
            var re = ('^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$');
		
			if (!from.match(re) || !to.match(re)) {
				alert(ol_QuickSearch_SingleServiceMissingDates);
				return;
			} 			
		} else if (this.searchType == 'Standard') {
			if($('#qs_datepicker_from').val() == 'yyyy-mm-dd' || $('#qs_datepicker_to').val() == 'yyyy-mm-dd') {
				alert(ol_err_select_both_dates);
				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 == '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 == '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('flight_only', 'false');
			c.set('service_id', selectedID)						
			c.set('arrival_destination_id', this.DestinationID);
			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_category_id', $('#qs_packagecategory_id').val());
			c.set('package_id', $('#qs_package_id').val());
		} else if (this.searchType == 'PackageSearch') {
			c.set('departure_date', $('#qs_datepicker_from').val());
			c.set('arrival_date', $('#qs_datepicker_to').val());
			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', '');
		}

  		if (!this.iframeSearch) {
			top.window.location.href = url;  
		} else {
			top.location.href = url;
		}
	}
});


/*	PACKAGE PAGE:
--------------------------------------------------------------------------------------------------------------------- */
var _thisPD = null;
PackageDetails = function(id, type, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL, currencyCode) {
	this.init(id, type, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL, currencyCode);
};
jQuery.extend( PackageDetails.prototype, {
	init: function(id, type, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems, startURL, currencyCode) {
		this.ID = id;
		this.GUID = guid;
		this.DestinationID = destinationID;
		this.ownerInfo = ownerInfo;
		this.MinimumFlightItems = parseInt(minFlightItems);
		this.MinimumHotelItems = parseInt(minHotelItems);
		this.MinimumServiceItems = parseInt(minServiceItems);
		this.MinimumCarItems = parseInt(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 = parseInt($('#p_adult_count').val());
		this.Children = parseInt($('#p_child_count').val());
		this.Infants = parseInt($('#p_infant_count').val());
		
		this.calculate();
	},
	calculate: function() {      
		this.Items = [];

		$('#message_box').html('').removeClass('message').removeClass('error').hide();
		$('#p_btn_continue').attr( 'disabled', 'true').hide();
		$('#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.Adults = parseInt($('#p_adult_count').val());
		_thisPD.Children = parseInt($('#p_child_count').val());
		_thisPD.Infants = parseInt($('#p_infant_count').val());
		
		_thisPD.Items = [];
		_thisPD.StaticItems = [];

		var itemInternalIDs = "";
		var itemStaticIDs = "";
		var departureDateID = 0;  
		var	departureDateCheck = false; 
		var err_msg = ol_SelectPackageDate;

		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;
					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] = parseInt(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;
			err_msg = ol_err_pkg_you_have_to_select_at_least_one_flight.replace('--', _thisPD.MinimumFlightItems - flightItems);
		} else if (hotelItems < _thisPD.MinimumHotelItems) {			
			minimumItemsCheck = false;
			err_msg = ol_err_pkg_you_have_to_select_at_least_one_hotel.replace('--', _thisPD.MinimumHotelItems - hotelItems);
		} else if (serviceItems < _thisPD.MinimumServiceItems) {
			minimumItemsCheck = false;
			err_msg = ol_err_pkg_you_have_to_select_at_least_one_service.replace('--', _thisPD.MinimumServiceItems - serviceItems);
		} else if (carItems < _thisPD.MinimumCarItems) {
			minimumItemsCheck = false;                   
			err_msg = ol_err_pkg_you_have_to_select_at_least_one_car.replace('--', _thisPD.MinimumCarItems - carItems);
		}  

		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) + " " + _thisPD.currencyCode + " ").show();
						$('.price-info').show();
						$('#p_btn_continue').removeAttr('disabled').show();
						$('#p_btn_continue').parent().removeClass('disabled');
						
						_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 {
					$('#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 {
			$('#message_box').html(err_msg).addClass('message').show();
			$('#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;    
		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') {
				_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') {
				_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 == null) {
			formId = "#OdinFormPage";
		} else {
			formId = "#" + formId;
		}
		
    if ($(formId).valid()) {
    	this.getGiftVoucherInfo();
			this.getCustomer();
			this.target = '';
      this.getPayments();		                         	
            
			var ip = $('#ip_address').val(); 
			var userComment = $('#customer_comments').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.customer, this.payments, this.giftVoucher, ip, userAgent, userComment, 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);
		}
  },
 	doBookingExternal: function (ownerInfoString,url) {
        var cb = $('.terms input')[0];
    
        if (!cb.checked) {
              alert(ol_PaymentTermsNotAgreed);
              return false;
    		}
    
        if ($("#SearchResultsForm").valid()) {
            this.getGiftVoucherInfo();
            this.getCustomer();
            this.payments = [];
            this.payments[this.payments.length] = new Zeus.Odin.DisillModules.Common.Payment();		                         
            
            var ip = $('#ip_address').val();
            var userAgent = navigator.userAgent;
            var userComment = '';
            var totalPrice = $('#total_price').val();
            
            $.fn.colorbox({
            	href: '#booking_loader',
            	inline: true,
            	initialWidth: 700,
            	initialHeight: 440,
            	width: 700,
            	height: 440,
            	overlayClose: false,
            	open:true
            });
            
            Zeus.Odin.DisillModules.API.OdinAPI.CreateBooking(ownerInfoString, this.customer, this.payments, this.giftVoucher, ip, userAgent, userComment,getCurrentPage(), function(r) {
            	this.result = 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 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();
	},
	getPayments: function() {
    this.payments = [];
    this.paymentItem = new Zeus.Odin.DisillModules.Common.Payment();
    this.paymentType = 'NotSelected';
      
 		this.paymentItem.CreditCardNumber = $('#cc_number').val();
		this.paymentItem.CreditCardExpiresMonth = $('#cc_valid_month').val();
		this.paymentItem.CreditCardExpiresYear = $('#cc_valid_year').val();
    this.paymentItem.CreditCardCcvNumber = $('#cc_ccv_code').val();
		this.paymentItem.CreditCardOwnerName = $('#cc_cardholder_name').val();		
    this.paymentItem.Amount =  $('#total_price').val();
   	this.paymentItem.CreditCardOwnerIdNumber = $('#cc_cardholder_idnumber').val();
        
    if($('#payment_options').val() == 'simple') {
        this.paymentItem.MethodID = $('#payment_method_id').val();
        this.paymentItem.Type = 'Direct';
        this.paymentItem.CreditCardType = $('#cc_type').val();
    } else {                                                 
        this.paymentItem.CreditCardNumberOfMonths = 0;
        this.paymentItem.MethodID = $('input:radio[name=paytype]:checked').attr('method_id');
        this.paymentItem.Type = $('input:radio[name=paytype]:checked').attr('ptype');
        this.paymentItem.CreditCardType = $('input:radio[name=paytype]:checked').attr('card');
        if (this.paymentItem.Type === 'Contract') {
            this.paymentItem.CreditCardNumberOfMonths = $('input:radio[name=paytype]:checked').attr('months'); 
            this.paymentItem.CreditCardPaymentDate = $('input:radio[name=paytype]:checked').attr('firstdate');
        }                                                                                   
    }
      
    this.payments[this.payments.length] = this.paymentItem;		                         
  },
	getGiftVoucherInfo: function() {
		this.giftVoucher = giftVoucherInfo;
	},
	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();
		}
	});
	
	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, calculatedPrices, mealPlanCalculatedPrices) {
	Zeus.Odin.DisillModules.API.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, pricing) {
	Zeus.Odin.DisillModules.API.OdinAPI.SaveCarInfo(typeID, from, to, price, pricing, 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 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(agreeTerms, forceSSL) {
	var inForceSSL = true;
	
	if (agreeTerms == null) {
		agreeTerms = true;
	}

	if (forceSSL != undefined) {
		inForceSSL = forceSSL;
	}

	if (validatePassengerForm() && AreTermsAgreed(agreeTerms) ) {
		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) {
			    if (inForceSSL) {
			    	top.window.location.href = 'https://' + location.host + r.NextUrl;
				} else {
					top.window.location.href = 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.splice(ind, 1);// = $.grep(this.SelectionIDs, 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.split('_')[0];
			serviceSelection.ServiceID = item.ServiceID;
			serviceSelection.ServiceItemID = item.ServiceItemID;
			serviceSelection.ServicePeriodID = item.ServicePeriodID;
			serviceSelection.Price = item.Price;
			serviceSelection.Pricing =  item.Pricing;
			
			selections[selections.length] = serviceSelection;
		});
		
		Zeus.Odin.DisillModules.API.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 }
		Zeus.Odin.DisillModules.API.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);
			}
		}, Error);		
	} 	
});

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();
	$('#multiple_cards').hide();
	$('.payment-info > .amount').addClass('hidden');
	$('.select-nr-of-cards').addClass('hidden');
	
	if (type == 'mc_contract') {
		$('#mc_months').show();
	} else if (type == 'visa_contract') {
		$('#visa_months').show();
	} else if (type == 'multiple') {
	 	$('#multiple_cards').show();
	 	$('.payment-info > .amount').removeClass('hidden');
		$('.select-nr-of-cards').removeClass('hidden');
	}
	SetNrOfCards(1);
}     

//Sets the number of cards that the customer wishes to pay with.			
function SetNrOfCards(nr){
	var nrCards = nr; 
	if(nrCards == null) {
		nrCards = parseInt($('#nr-of-cards').val());
	}
	
	var totalAmount = parseInt($('#total_price').val()) - parseInt($('#gift_voucher_amount').val());
	var amountEach = Math.floor(totalAmount / nrCards);
		
	//$('.payment-info').addClass('hidden');
	for(var i = 1; i < nrCards+1; i++){
	  $('.card-' + i).removeClass('hidden').find('#amount').val(amountEach);
	}					
	
	//Set the last amount
	CalculateRemainingAmount(nrCards);
}

function CalculateRemainingAmount(nr) {      
	var nrCards = nr; 
	if(nrCards == null) {
		nrCards = parseInt($('#nr-of-cards').val());
	} 
	$('.payment-info').find('#amount').removeAttr('disabled');
	if(nrCards > 1) {
		var totalAmount = parseInt($('#total_price').val()) - parseInt($('#gift_voucher_amount').val());
		var totalAllocated = 0;
		for(var i = 1; i < nrCards; i++) {
			totalAllocated += parseInt($('.card-' + i).find('#amount').val());
		}
		$('.card-' + nrCards).find('#amount').val( totalAmount - totalAllocated).attr('disabled','disabled');		
	}
}

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);
			$('#gift_voucher_amount').val(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));
			CalculateRemainingAmount();
		} else {
			alert('Gjafabréf með númerinu sem þú slóst inn fannst ekki.');
		}
	}, Error);
}
/*	----------< MY PAGES >------------------------------------------------------------------------------------------------ */
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);
}

/*	--< HOTEL PRICE CHECK >------------------------------------------------------ */
function GetHotelPriceQuote(ownerInfo, hotelID, startUrl) {
	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();
	var __ownerInfo = ownerInfo;
	var __startUrl = startUrl;
	
	$('.price-quote .loader').show();
	$('.price-quote #results').empty();
	
	tmr = $.timer(1000, function() {
		Zeus.Odin.DisillModules.API.OdinAPI.HotelPriceQuote(__ownerInfo, hotelID, from, to, adults, children, infants, 1, function(r) {
			var html = '';
	    if (r.length > 0) {
				$.each(r, function() {
					if (this.MealPlan) {
					    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">' + addCommas(this.PricePrPerson.toFixed(2)) + ' EUR</span></span>' +
								'<span class="price total">' + ol_PriceQuote_Price + ':<br /><span class="blue">' + addCommas(this.Price.toFixed(2)) + ' 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 + ', \''+ __startUrl +'\', \''+ this.CalculatedPrice.Encrypted +'\', \''+ this.MealPlan.CalculatedPrice.Encrypted +'\');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">' + addCommas(this.PricePrPerson.toFixed(2)) + ' EUR</span></span>' +
								'<span class="price total">' + ol_PriceQuote_Price + ':<br /><span class="blue">' + addCommas(this.Price.toFixed(2)) + ' EUR</span></span>' +
							    '<span class="book-now"><a class="book" href="#book-room" onclick="SelectRoomFromPriceQuote(\'' + __ownerInfo + '\', ' + this.HotelID + ', ' + this.ID + ',0, ' + this.Price + ',0,\''+ __startUrl +'\', \''+ this.CalculatedPrice.Encrypted +'\', \'\');return false;">' + ol_PriceQuote_BookNow + '</a></span>' +
							'</div>';
						}
				});                   
			} else {
				html = '<div class="error">' + ol_PriceQuote_NoResult + '</div>';
			}

			$('.price-quote #results').html(html);
			$('.price-quote .loader').hide();
		}, Error);
	});
}

function SelectRoomFromPriceQuote(ownerInfo, hotelID, roomTypeID, mealPlanID, price, mealPlanPrice, startUrl, hotelPricing, mealPlanPricing) {
	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);
	c.set('set_calculated_prices', hotelPricing)
	c.set('set_mealplan_calculated_prices', mealPlanPricing)

	// SEND TO START PAGE:
	top.window.location.href = startUrl;
}

// ---------------------------------------------------------------------------------------------------------------
/* JSON SUPPORT:
	USED FOR THE COOKIEJAR PLUGIN 
	--------------------------------------------------------------------------------------------------------------------- */
(function ($) {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'array': function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            'number': function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};
	
	$.parseJSON = function(v, safe) {
		if (safe === undefined) safe = $.parseJSON.safe;
		if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
			return undefined;
		return eval('('+v+')');
	};
	
	$.parseJSON.safe = false;

})(jQuery);

