$(document).ready(function() {
	loadBanners();
	loadItems();
	return false;
});

// Search Switcher
function switchSearch(searchType, subType) {
	$('.package-types ul.selector li').removeClass('on');
	$('ul.selector li[index=' + subType + ']').addClass('on');
	$('.tours, .accs').addClass('hidden');

	//$('.package-types .container .part, .pers').addClass('hidden');
	//$('.package-types .container .part[search_type=' + searchType + ']').removeClass('hidden');
	
	quickSearch.searchType = searchType;
	$.cookie('ODIN_SEARCH_TYPE', subType, { path: '/', expires: 7, cookiePrefix: '' });
		
	if (subType == '1') {
		quickSearch.urls = 'Package|Passengers|Payment|Receipt';
		$('#qs_search_button').attr('value', 'Go to tour');
		$('.tours, .pers').removeClass('hidden');
		$('#qs_search_button').removeClass('hidden');
	} else if (subType == '2') {
		quickSearch.urls = 'Hotels|Passengers|Payment|Receipt';
		$('#qs_search_button').attr('value', ' Search ');
		$('.pers').removeClass('hidden');
		$('#qs_search_button, .check-in, .check-out, .accs').removeClass('hidden');
		$('.check-in label').html('Check in:');
		$('.check-out label').html('Check out:');
	} else if (subType == '3') {
	    quickSearch.urls = 'Cars|Passengers|Payment|Receipt';
		$('.pers').addClass('hidden');

		$('#qs_search_button, .check-in, .check-out, .destination, .accs').removeClass('hidden');

		$('.check-in label').html('From:');
		$('.check-out label').html('To:');
		$('#qs_search_button').attr('value', ' Search ');
	}
} 

function checkInChanged(dateText, inst) {
	$('.check-out input').datepicker('option', 'minDate', new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
}

function checkOutChanged(dateText, inst) {
	$('.check-in input').datepicker('option', 'maxDate', new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
}

//----------------------------------- FRONT PAGE BANNERS/CAROUSEL ------------------------------------//
var bannerIdx = 0;
var bannerCount = 0;
var timerCount = 0;

function loadItems() {
	$('.fp-items .item').hover(
		function () {
			$($(this).children('.cont').get(0)).stop().animate({top:'0'}, 300, 'linear', function() {});
		},
		function () {
			$($(this).children('.cont').get(0)).stop().animate({top:'86px'}, 300, 'linear', function() {});
		}
	).click(function() {
		top.window.location.href = $(this).find('.cont .more a').attr('href');
	});
}

function loadBanners() {
	bannerCount = $('#banners .banner').length;
	bannerIdx = 0;
	
	if (bannerCount > 1) {
		showBanner(+1);
	} else {
		$('#banners div.banner:eq(0)').fadeIn(300);
	}
}

function showBanner(increase) {
	$('#banners div.banner:eq(' + bannerIdx + ')').fadeOut(300);
            
	bannerIdx = (bannerIdx + increase + bannerCount) % bannerCount;
          		                 
	$('#banners div.banner:eq(' + bannerIdx + ')').fadeIn(300, function() {   
		timerCount++;      
  		$.timer(10000, function() {
  			if(timerCount == 1) {
				showBanner(+1);
			}
			timerCount--;
		});            
	});
}

/*	PACKAGE PAGE:
--------------------------------------------------------------------------------------------------------------------- */
var _thisPD = null;
PackageDetailsICEO = function(id, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL, currencyCode) {
	this.init(id, guid, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems,startURL, currencyCode);
};
jQuery.extend( PackageDetailsICEO.prototype, {
	init: function(id, guid, type, destinationID, ownerInfo, minFlightItems, minHotelItems, minServiceItems, minCarItems, startURL, currencyCode) {
		this.ID = id;
		this.GUID = guid;
		this.DestinationID = destinationID;
		this.ownerInfo = ownerInfo;
		this.MinimumFlightItems = minFlightItems;
		this.MinimumHotelItems = minHotelItems;
		this.MinimumServiceItems = minServiceItems;
		this.MinimumCarItems = minCarItems;
		this.Items = [];
		this.StaticItems = [];
		this.TotalPrice = 0;
		this.StartUrl = startURL;
		this.Type = type;
		
		if (currencyCode == null) {
			this.currencyCode = 'EUR';
		} else {
			this.currencyCode = currencyCode;
		}

		var c = $.cookieJar('ODIN-BOOKING-DATA', { cookiePrefix: '' });

		if (c != null) {
			$('#p_adult_count').val(c.get('adult_count'));
			$('#p_child_count').val(c.get('child_count'));
			$('#p_infant_count').val(c.get('infant_count'));  
			this.CategoryID = c.get('package_category_id'); 
		}
		
		this.Adults = $('#p_adult_count').val();
		this.Children = $('#p_child_count').val();
		this.Infants = $('#p_infant_count').val();
		
		this.calculate();
	},
	calculate: function() {      
		this.Items = [];

		//$('#p_btn_continue').disabled = true;
		$('#p_btn_continue').attr( 'disabled', 'true' );
		$('#p_btn_continue').parent().addClass('disabled');
		$('#p_btn_calculate').attr( 'disabled', 'true' );
		$('#p_btn_calculate').parent().addClass('disabled');
		$('#price_loader').show();                   
		$('#results_cont').show();
		$('#p_error_msg').hide();

		_thisPD = this;
		$.timer(500, this.perform);
	},
	perform: function() {
		var flightItems = 0;
		var hotelItems = 0;
		var serviceItems = 0;
		var carItems = 0;
		var minimumItemsCheck = true;
	    _thisPD.Items = [];
		_thisPD.StaticItems = [];
   		var itemInternalIDs = "";
		var itemStaticIDs = "";
		var departureDateID = 0;

		$('span.cb').each(function(i, item) {
			var itemID = $(item).attr('itemid');
			var itemType =  $(item).attr('itemtype');			
			var inventoryType = $(item).attr('iteminventorytype');
			
			if (inventoryType == 'Internal') {
				if ($('#packageItem_' + itemID + ':checked').length > 0 ) {
					_thisPD.Items[_thisPD.Items.length] = itemID;
					itemInternalIDs += itemID + '|';

					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}
				}
			} else if (inventoryType == 'Static') {
				if ($('#packageItem_'+itemID + ':checked').length > 0) {
					_thisPD.StaticItems[_thisPD.StaticItems.length] = itemID;
					itemStaticIDs += itemID + '|';
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}
				}
			}
		});
		
		if (flightItems < _thisPD.MinimumFlightItems) {		
			minimumItemsCheck = false;
		} else if (hotelItems < _thisPD.MinimumHotelItems) {			
			minimumItemsCheck = false;
		} else if (serviceItems < _thisPD.MinimumServiceItems) {
			minimumItemsCheck = false;
		} else if (carItems < _thisPD.MinimumCarItems) {
			minimumItemsCheck = false;
		}  
		
		_thisPD.Adults = $('#p_adult_count').val();
		_thisPD.Children = $('#p_child_count').val();
		_thisPD.Infants = $('#p_infant_count').val();
		
		if (minimumItemsCheck && (_thisPD.Items.length + _thisPD.StaticItems.length) > 0) {
			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(" --- ");
			$('#results_cont').hide();
			$('#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;

		
		$('span.cb').each(function(i, item) {
			var itemID =  $(item).attr('itemid');
			var itemType =  $(item).attr('itemtype');
			var inventoryType = $(item).attr('iteminventorytype');
			
			if (inventoryType == 'Internal') {
				if ($('#packageItem_'+itemID + ':checked').length > 0) {
					_thisPD.Items[_thisPD.Items.length] = itemID;
					itemInternalIDs += itemID + '|';
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}		
				}
			} else if (inventoryType == 'Static') {
				if ($('#packageItem_'+itemID + ':checked').length > 0) {
					_thisPD.StaticItems[_thisPD.StaticItems.length] = itemID;
					itemStaticIDs += itemID + '|';
					switch(itemType) {
						case 'Flight': flightItems++; break;
						case 'Hotel': hotelItems++;	break;
						case 'Service':	serviceItems++;	break;
						case 'Car': carItems ++; break;
						default : break;
					}		
				}							
			}	
		});  
				
		if (flightItems < _thisPD.MinimumFlightItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_flight.replace('--', _thisPD.MinimumFlightItems));
		} else if (hotelItems < _thisPD.MinimumHotelItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_hotel.replace('--', _thisPD.MinimumHotelItems));
		} else if (serviceItems < _thisPD.MinimumServiceItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_service.replace('--', _thisPD.MinimumServiceItems));
		} else if (carItems < _thisPD.MinimumCarItems) {
			minimumItemsCheck = false;
			alert(ol_err_pkg_you_have_to_select_at_least_one_car.replace('--', _thisPD.MinimumCarItems));
		}

		if (minimumItemsCheck) {
			//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);           
			c.set('package_id', _thisPD.GUID);
			c.set('package_category_id', _thisPD.CategoryID);
			
			top.window.location.href = _thisPD.StartUrl;
		}
	}
});


/*	CONTACT US:
--------------------------------------------------------------------------------------------------------------------- */
SendEmail = function(btn, subject, to, sendCopy) {
  this.init(btn, subject, to, sendCopy);
};
jQuery.extend(SendEmail.prototype, {
	init: function(btn, subject, to, sendCopy) {
		var qs = 'i_subject=' + subject + '&i_to=' + to;
				
		var items = $('input.email-form-item, select.email-form-item, textarea.email-form-item').each(
			function(i, el) {
				qs += '&' + $(el).attr('id') + '=' + $(el).val();
			}
		);
		
		if (sendCopy !== null) {
			qs += '&sc=true&sct=' + $('.email-send-copy-to').val()
		} else {
			qs += '&sc=false';
		}

		$.post('/Modules/Forms/Submit.aspx', qs, function(r) {
			if(r == 'true') {
				alert('Message has been sent.'); 
				$('#Name').val(''); 
				$('#Email').val('');
				$('#Message').val('');
			} else {
				alert('An error occured while sending the request.');
			}   

			btn.disabled = false;
			btn.value = 'Send';	
		}, function(e) {
			alert('An error occured while sending the request.');
		});
	}
});


function verifycontactform(btn) {
	btn.disabled = true;
	btn.value = 'Sending message now ...';
	var message = 'Please fill out: ';
	var isGood = true;
	var emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	
	if ( $('#email').val() == "") {
		message = message + "\n -  Email";
		isGood = false;
	}
	if ( $('#message').val() == "") {
		message = message + "\n -  Message";
		isGood = false;
	}
	if (!$('#email').val().match(emailRegEx) ) {
		message = message + "\n -  Email";
		isGood = false;
	}                                       
	
	if (isGood) {
		new SendEmail(btn, 'Iceland Online - Contact', 'info@icelandonline.com', $('#email_include_me:checked'));
	} else {
		alert(message);
		btn.disabled = false;
		btn.value = 'Send';
	}

	return isGood;
}


/*	HOTEL IMAGE THINGY:
	--------------------------------------------------------------------------------------------------------------------- */
HotelImageMovers = function() {
  this.init();
};
jQuery.extend(HotelImageMovers.prototype, {
	init: function() {
		this.UL = $('div.thumbnails ul');
		
		this.Positions = new Array();
		this.CurrentPosition = 0;		
		var containingClass = this;
		
		$('img.hotel-thumb').each( function(i, element) {
				$(element).click( function(ev) {
				$('#hotel_image_loader').show();
				
				$('#main_image').fadeTo("slow",0, function(){
					var engine = $(element).attr('engine');
					if( engine == "getfile") {
						var procID = $(element).attr('procID');
						var imageID = $(element).attr('imgID');
						$('#main_image').attr('src', "/modules/odin/getfile.aspx?fileid=" + imageID + "&processid=" + procID);
											
						$('#main_image').fadeTo("def",1,(function() {	
							$('#hotel_image_loader').hide();
						}));
					} else {
						var hotel_id = $(element).attr("hotel_id");
						var filename = $(element).attr("filename");
						$('#main_image').attr('src', "/Modules/Odin/ImageHost.aspx?MaxHeight=320&MaxWidth=510&Quality=60&HotelID=" + hotel_id + "&FileName=" + filename );
											
						$('#main_image').fadeTo("slow",1,(function() {	
							$('#hotel_image_loader').hide();
						}));	
					}
				});
				
			});		
			containingClass.Positions[containingClass.Positions.length] = parseInt($(element).height()) + 8;
		});

		if ($('#move_up')) {
			$('#move_up').bind('click', function(event) {
				if (containingClass.CurrentPosition > 0) {					
					containingClass.CurrentPosition = containingClass.CurrentPosition - 1;
					var currentPosY = 0;
					
					for (var i = 0; i < containingClass.CurrentPosition; i++) {
						currentPosY = currentPosY + containingClass.Positions[i];
					}
					
					containingClass.UL.animate({ 
				        top: (currentPosY * -1) + 'px'
				      }, 350 );
				}
			});
		}

		if ($('#move_down')) {
			$('#move_down').bind('click', function(event) {
				if (containingClass.CurrentPosition < (containingClass.Positions.length - 1)) {
					containingClass.CurrentPosition = containingClass.CurrentPosition + 1;
					var currentPosY = 0;
					
					for (var i = 0; i < containingClass.CurrentPosition; i++) {
						currentPosY = currentPosY + containingClass.Positions[i];
					}
					containingClass.UL.animate({ 
				        top: (currentPosY * -1) + 'px'
				      }, 350 );
				}
			});
		}
	}
});

function ShowHotelImage() {
	$('#hotel_image_loader').hide();
	if (HIS != null) {
		$('#main_image').fadeTo("def",1);			
	}
}

