/**
 * SEARCH & BOOK MODULE
 */
var selectedType = "room";
var containerId = "";

	/**
	 * Search and Book object
	 * @param {Object} options
	 */
var SearchBook = base2.Base.extend({
	constructor: function(options) {
		this.SetOptions(options);
		this.LoadTemplates();
	},

	Options: {},

	Templates: {},

	Element: null,

	ContainerID: "",

	SetOptions: function(options) {
		this.Defaults = {
			ElementID: "searchBook",
			Selector: "#searchBook",
			Channel: GBPChannel,
			Template: "templates/gbp_searchbook.html",
			ItemTemplate: "templates/gbp_searchbook_item.html",
			API: GBPServiceUrl + "/{channelID}/quicksearch/rooms",
			Level1API: GBPServiceUrl + "/{channelID}/destinations",
			Level2API: GBPServiceUrl + "/{channelID}/destination/{locationID}/products",
			DestinationsSelector: "#destinations",
			OptionsSelector: ".popup .scroller ul",
			ProductsSelector: "#products",
			ProvidersSelector: "#providers",
			BookButtonSelector: "#btnConfirmBookNow",
			ThumbnailDefault: "",
			ShowDestinations: true,
			PopupScrollerHeight: 275
		}

		this.Options = jQuery.extend({}, this.Defaults, options);

	},

	LoadTemplates: function() {
		this.Templates.Main = LoadTemplate(this.Options.Template);
		this.Templates.Item = LoadTemplate(this.Options.ItemTemplate);
	},

	setEvents: function() {
		var object = this;
		
		jQuery(this.Options.BookButtonSelector).hide();

		/** DESTINATIONS **/
		jQuery(this.Options.Selector).find(this.Options.DestinationsSelector).click(function() {
			//var popup = jQuery(this).toggleClass("active");
			var li = jQuery(this);
			var popup = li.find(".popup");

			if (li.hasClass('active')) {
				popup.stop(true, false).fadeOut(300, function() {
					li.removeClass("active");
				});
			} else {
				popup.hide();
				if (jQuery.browser.msie) {
					popup.stop(true, false).css({
						display: "block",
						opacity: 1
					});
				}
				else {
					popup.stop(true, false).css({
						display: "block",
						opacity: 0
					}).animate({
						opacity: 1
					});
				}
				li.addClass("active");
			}

		});

		jQuery(this.Options.Selector).find(this.Options.DestinationsSelector).mouseleave(function() {
			var container = jQuery(this);
			var popup = jQuery(this).find(".popup");
			//var container = popup.parent();

			if (container.hasClass('active')) {
				popup.stop(true, false).fadeOut(300, function() {
					container.removeClass("active");
					popup.find(".scroller ul").css({ top: 0 });
				});
			}


		});


		// Handle the select on the destination option
		jQuery(this.Options.Selector).find(this.Options.DestinationsSelector).find(".popup").delegate(".item", "click", function() {
			var value = jQuery(this).attr("rel");
			object.SetDestination(value);
		});


		/** PROVIDERS **/
		jQuery(this.Options.Selector).find(this.Options.ProvidersSelector).click(function() {
			var li = jQuery(this);
			var popup = li.find(".popup");

			// Check if items greater than 1 (ie: worth showing the dropdown)
			if (popup.find(".scroller li").length <= 1) {
				return false;
			}

			if (li.hasClass('active')) {
				popup.stop(true, false).fadeOut(300, function() {
					li.removeClass("active");
				});
			} else {
				popup.hide();
				if (jQuery.browser.msie) {
					popup.stop(true, false).css({
						display: "block",
						opacity: 1
					});
				}
				else {
					popup.stop(true, false).css({
						display: "block",
						opacity: 0
					}).animate({
						opacity: 1
					});
				}
				li.addClass("active");
			}
		});

		jQuery(this.Options.Selector).find(this.Options.ProvidersSelector).mouseleave(function() {
			var container = jQuery(this);
			var popup = jQuery(this).find(".popup");
			//var container = popup.parent();

			if (container.hasClass('active')) {
				popup.stop(true, false).fadeOut(300, function() {
					container.removeClass("active");
					popup.find(".scroller ul").css({ top: 0 });
				});
			}

		})

		// Handle the select on the destination option
		jQuery(this.Options.Selector).find(this.Options.ProvidersSelector).find(".popup").delegate(".item", "click", function() {
			var value = jQuery(this).attr("rel");
			object.SetProvider(value);
		});


		/** PRODUCTS **/
		jQuery(this.Options.Selector).find(this.Options.ProductsSelector).click(function() {
			//var popup = jQuery(this).toggleClass("active");

			var li = jQuery(this);
			var popup = li.find(".popup");			

			// Check if items greater than 1 (ie: worth showing the dropdown)
			if (popup.find(".scroller li").length <= 1) {
				return false;
			}

			if (li.hasClass('active')) {
				popup.stop(true, false).fadeOut(300, function() {
					li.removeClass("active");
				});
			} else {
				popup.hide();
				if (jQuery.browser.msie) {
					popup.stop(true, false).css({
						display: "block",
						opacity: 1
					});
				}
				else {
					popup.stop(true, false).css({
						display: "block",
						opacity: 0
					}).animate({
						opacity: 1
					});
				}
				li.addClass("active");
			}

		});

		jQuery(this.Options.Selector).find(this.Options.ProductsSelector).mouseleave(function() {
			var container = jQuery(this);
			var popup = jQuery(this).find(".popup");
			//var container = popup.parent();

			if (container.hasClass('active')) {
				popup.stop(true, false).fadeOut(300, function() {
					container.removeClass("active");
					popup.find(".scroller ul").css({ top: 0 });
				});
			}

		})


		//Don't close the dropdown when clicking on the up/down arrows
		jQuery(this.Options.Selector + " .popup").delegate(".scroll .up, .scroll .dn", "click", function(event) {
			return false;
		});


		jQuery(this.Options.Selector + " .popup").delegate(".scroller", "mousemove", function(event) {

			var window = jQuery(this);
			var windowHeight = window.height();

			var scroller = jQuery(this).find("ul");
			var scrollerHeight = scroller.height();

			if (scrollerHeight > windowHeight) {

				var windowOffset = window.offset();
				var windowX = windowOffset.left;
				var windowY = windowOffset.top;

				var windowInnerX = event.pageX - windowX;
				var windowInnerY = event.pageY - windowY;

				var scope = scrollerHeight - windowHeight

				var newTop = -windowInnerY / windowHeight * scope;
				scroller.css({
					top: newTop
				});

			} else {
				scroller.css({
					top: 0
				});
			}
		});



		jQuery(this.Options.ProductsSelector).find(".popup").delegate(".item", "click", function() {
			var value = jQuery(this).attr("rel");

			object.SetProduct(value);


		});

		/** 
		* CONFIRM & BOOK NOW
		* ================== 
		**/
		jQuery(this.Options.Selector).delegate(this.Options.BookButtonSelector, "click", function() {
			//Check that product is selected
			//productSelector.Open(object.SelectedProductData());

			//loader.Show("<img src='images/gbp/loading.gif' /><br/>Loading");
			//loader.Show();
			productSelector.ProductData = object.SelectedProductData();
			var workingKey = GUID();

			if (cartID.length > 0) {
				productSelector.Cart = new Cart({
					AutoRefresh: false,
					WorkingKey: workingKey,
					CartID: cartID
				});
			} else {
				productSelector.Cart = new Cart({
					AutoRefresh: false,
					WorkingKey: workingKey
				})
			}
			productSelector.Options.LoadCart = false; // Do not load the cart when displaying
			//productSelector.ScopeID = workingKey; // Generate a GUID for the temporary purchase object

			productSelector.OrderGuid = "";
			productSelector.WorkingKey = workingKey;

			productSelector.SetDatePicker(object.SelectedDate());

			cart.ClearWorking();


			productSelector.Show();

			return false;
		});


		// Datepicker
		jQuery(this.Options.Selector).find('.datepicker').each(function() {
			var a = jQuery('.trigger', this);
			jQuery(this).append('<div class="datepopup"></div>');
			jQuery('.datepopup', this).datepicker({
				inline: true,
				dateFormat: 'dd MM yy',
				onSelect: function(date, inst) {
					a.find('span').html(date.toUpperCase()).end().
							parents('.datepicker').
								removeClass('datepicker-active').
								find('input[type="hidden"]').val(date).end();
					object.SetDate(inst.selectedYear, inst.selectedMonth, inst.selectedDay);

					if (object.Cart) {
						object.MapPurchase(object.Cart.Purchase);
					}
				}
			});
			jQuery('.trigger', this).click(function() {
				jQuery(this.parentNode).toggleClass('datepicker-active');
				return false;
			});
		});

	},

	/** 
	* Primary Function to load a Search & Book module into a page
	* @param {Selector} Selector for the container to render the module within
	*/
	Load: function(container) {
		this.Render(container);
		this.LoadDestinations();
	},

	/**
	* Render the html into the specified container
	* (requires jQuery
	* @param {Object} container
	*/
	Render: function(container) {
		var object = this;
		if (container == undefined) {
			container = this.Element;
		}

		//containerId = container;
		this.ContainerID = container;

		var template = this.Templates.Main;
		template = jQuery(template);
		template.attr({ id: this.Options.ElementID });
		this.Options.Selector = "#" + this.Options.ElementID;

		template.find(this.Options.ProductsSelector).css({ visibility: "hidden" });

		var itemTemplate = this.Templates.Item;

		jQuery(container).append(template);

		this.Element = jQuery(this.Options.Selector);

		this.setEvents();
		this.Element.disableTextSelect();

		//set default date
		var today = Date.parse('today');
		this.SetDate(today.toString("yyyy"), today.toString("MM") - 1, today.toString("dd"));
	},

	SetDate: function(year, month, day) {

		if (day.charAt(0) == "0") {
			day = day.substr(1, day.length);
		}

		var dateObj = {
			year: parseInt(year),
			month: parseInt(month),
			day: parseInt(day)
		}

		var date = new Date().set(dateObj);

		this.SetDatePicker(date);
	},

	SetDatePicker: function(date) {
		jQuery(this.Options.Selector).find(".datepopup").datepicker("setDate", date);
		jQuery(this.Options.Selector).find(".datepicker .trigger span").text(date.toString("dd MMM yyyy"));
	},


	/**
	* Selected Date Picker
	*/
	SelectedDate: function() {
		var dateContainer = jQuery(this.Options.Selector).find(".datepopup");
		var dateData = dateContainer.data("datepicker");

		var dateObj = {
			year: dateData.selectedYear,
			month: dateData.selectedMonth,
			day: dateData.selectedDay
		}

		var date = new Date().set(dateObj).clearTime();

		return date;

	},

	/**
	* Make the API call for Data.
	*/
	LoadData: function() {
		//Destination Data

		var response = new APIHandler({
			Url: this.Options.API.replace("{channelID}", this.Options.Channel) + "?" + CacheBuster(),
			Method: APIMETHODS.GET
		}).Response;


		if (response.Result) {
			this.Data = response.Value;
			jQuery(this.Options.Selector).removeClass("loading");
			return this.Data;
		} else {
			ShowError("Quick Book API error");
			return false;
		}
	},

	/**
	* Load destination objects into the list
	* @param {Object} data
	*/
	LoadDestinations: function(data) {
		if (data == undefined) {
			data = this.LoadData();
		}

		if (data.Destinations.length == 0) return false;

		var dest = this.Element.find(this.Options.DestinationsSelector);
		var destTemplate = this.Templates.Item;
		var destOptions = dest.find(this.Options.OptionsSelector)
		destOptions.empty();



		if (data) {

			var destCounter = 0;
			base2.Array2.forEach(data.Destinations, function(destination) {
				var item = destTemplate;
				item = item.replace("%NAME%", destination.Name);
				item = item.replace("%CAPTION%", destination.Location.Name);
				item = item.replace("%VALUE%", destination.Location.LocationId);
				item = item.replace("%IMAGE%", destination.Image);
				item = jQuery(item);
				item.data("destination", destination);
				item.find("span").hide();
				destOptions.append(item);

				destCounter++;
			});
		}

		//JL 21/10/2010: Rather than display first item, display some info i.e. "Choose your destination"
		//Default the selection to the first one in the list
		//this.SetDestination(destOptions.find(".item:first").parent().data("destination").Location.LocationId);
		var valueElement = dest.find(".item.value");
		valueElement.html("<img alt='' src='/images/gbp/icons/map-th-tasmania.gif'><strong>Choose your destination</strong>");
		this.ResetProvider();

		// Determine if top level destinations should be shown (typically hidden for casino sites)
		if (!this.Options.ShowDestinations) {
			dest.hide();
			this.SetDestination(this.Data.Destinations[0].Location.LocationId);
		}

		// Determine if dropdown style should be kept or change to no-drop
		if (destCounter <= 1) {
			dest.find(".item.value").addClass("no-drop");
		}
		
		//hide the button until they select a room
		jQuery(this.Options.BookButtonSelector).hide();

	},


	/// LOAD PROVIDER DATA
	LoadProviders: function(data) {
		if (data == undefined) {
			data = this.SelectedDestinationData();
		}

		var providerElement = jQuery(this.Options.Selector).find(this.Options.ProvidersSelector);
		var providerTemplate = this.Templates.Item;
		var providerOptions = providerElement.find(this.Options.OptionsSelector)
		providerOptions.empty().css({ top: 0 });

		var providerCount = 0;

		base2.Array2.forEach(data.Providers, function(provider) {
			providerCount++;
			var providerName = provider.Name.Media[0].Label.Text;
			var thumbnail = provider.Name.Media[0].Url;

			var item = providerTemplate;
			item = item.replace("%NAME%", providerName);
			item = item.replace("%CAPTION%", "");
			item = item.replace("%VALUE%", provider.Identifier);
			if (thumbnail && thumbnail.length > 0 && thumbnail != null) {
				item = item.replace("%IMAGE%", thumbnail);
			} else {
				//TODO: Set default thumbnail url
				item = item.replace("%IMAGE%", "images/gbp/no-thumb.gif");
			}

			item = jQuery(item);
			item.find("span").remove();
			item.data("provider", provider);
			providerOptions.append(item);
		});

		// Determine if top level destinations should be shown (typically hidden for casino sites)
		// Convert the provider level the larger dropdown format
		if (!this.Options.ShowDestinations) {
			providerElement.removeClass("lev2").addClass("lev1");
			providerElement.find(".level2").removeClass("level2").addClass("level1");
			providerElement.find(".popup2").removeClass("popup2").addClass("popup1");
		}

		// Determine if dropdown style should be kept or change to no-drop
		if (providerCount <= 1) {
			providerElement.find(".item.value").addClass("no-drop");
		} else {
			providerElement.find(".item.value").removeClass("no-drop");
		}
		

	},

	/**
	* @param {Object} data
	*/
	LoadProducts: function(data) {
		if (data == undefined) {
			data = this.SelectedDestinationData();
		}

		var prod = jQuery(this.Options.Selector).find(this.Options.ProductsSelector);
		var prodTemplate = this.Templates.Item;
		var prodOptions = prod.find(this.Options.OptionsSelector);
		prodOptions.empty().css({ top: 0 });

		var productCount = 0;
		base2.Array2.forEach(data.Products, function(product) {

			if (product.ProductName != "") { // Check against blank products
				var item = prodTemplate;
				//var title = GetContent(product.Content, "ProductTitle");

				var thumbnail = GetContent(product.Content, "Quickbook");
				var thumbnailMatch = GetContent(thumbnail.Media, "thumbnail");

				item = item.replace("%NAME%", product.ProductName);
				item = item.replace("%CAPTION%", product.ProductType);
				item = item.replace("%VALUE%", product.ProductCode);
				if (thumbnail && thumbnailMatch && thumbnailMatch.Url != null) {
					item = item.replace("%IMAGE%", thumbnailMatch.Url);
				} else {
					//TODO: Set default thumbnail url
					item = item.replace("%IMAGE%", "images/gbp/no-thumb.gif");
				}

				item = jQuery(item);
				item.find("span").remove();
				item.data("product", product);
				prodOptions.append(item);

				productCount++;
			}
		});

		// Determine if dropdown style should be kept or change to no-drop
		if (productCount <= 1) {
			prod.find(".item.value").addClass("no-drop");
		} else {
			prod.find(".item.value").removeClass("no-drop");
		}


		this.ShowProducts();
		
		// Determine if the popup height needs to be set. (Only if the items is in excess of 215 px height.
		var items = prod.find(".popup2 .scroller .item").length;
		var calculatedItemsHeight = items * 54;
		if (calculatedItemsHeight > this.Options.PopupScrollerHeight) {
			prod.find(".popup2 .scroller").css({ height: this.Options.PopupScrollerHeight});
			//prod.find(".popup2").css({ height: 315});
		} else {
			prod.find(".popup2 .scroller").css({ height: "auto"});
			//prod.find(".popup2").css({ height: "auto"});
		}
	},

	ShowProducts: function() {
		this.Element.find(this.Options.ProductsSelector).css({ visibility: "visible" });
	},

	HideProducts: function() {
		this.Element.find(this.Options.ProductsSelector).css({ visibility: "hidden" });
	},

	/**
	* Set the destination to the specified ID
	* @param {Object} locationID
	*/
	SetDestination: function(locationID) {


		//Find the specified ID in the list of options
		var dest = this.Element.find(this.Options.DestinationsSelector);
		var destOptions = dest.find(this.Options.OptionsSelector)

		var selected = destOptions.find("div[rel=" + locationID + "]");
		var selectedData = selected.parent().data("destination");
		var selectedHtml = selected.html();

		var valueElement = dest.find(".item.value");
		valueElement.html(selectedHtml);
		valueElement.data("destination", selectedData);

		this.LoadProviders(selectedData);
		this.ResetProvider();

		this.LoadProducts(selectedData);
		this.ResetProduct();

		// Set the default provider if there is only 1 (ie: first one)
		if (selectedData.Providers.length == 1) {
			var providerID = selectedData.Providers[0].Identifier;
			this.SetProvider(providerID);
		}
	},

	/**
	* Set the provider 
	* @param {Object} providerID
	*/
	SetProvider: function(providerID) {

		var provider = this.Element.find(this.Options.ProvidersSelector);
		var providerOptions = provider.find(this.Options.OptionsSelector)

		var selected = providerOptions.find("div[rel=" + providerID + "]");
		var selectedData = selected.parent().data("provider");
		var selectedHtml = selected.html();

		var valueElement = provider.find(".item.value");
		valueElement.html(selectedHtml);
		valueElement.data("provider", selectedData);

		this.LoadProducts(selectedData);
		this.ResetProduct();

		// Set the default product if there is only 1 (ie: first one)
		if (selectedData.Products.length == 1) {
			var productCode = selectedData.Products[0].ProductCode;
			this.SetProduct(productCode);
		}
		
		//hide button until they select a room
		jQuery(this.Options.BookButtonSelector).hide();
	},

	/**
	* Get the selected destination
	*/
	SelectedDestinationData: function() {
		var destData = this.Element.find(this.Options.DestinationsSelector).find(".level1").data("destination");

		return destData;

	},

	/**
	* Get the provider data
	*/
	SelectedProviderData: function() {
		var providerData = this.Element.find(this.Options.ProvidersSelector).find(".level2").data("provider");
	},

	/** 
	* Get the selected product
	*/
	SelectedProductData: function() {
		var prodData = this.Element.find(this.Options.ProductsSelector).find(".level2").data("product");

		return prodData;
	},

	/**
	* Set the Product
	* @param {Object} productCode
	*/
	SetProduct: function(productCode) {
		var prod = this.Element.find(this.Options.ProductsSelector);
		var prodOptions = prod.find(this.Options.OptionsSelector);

		var selected = prodOptions.find("div[rel=" + productCode + "]");
		var selectedData = selected.parent().data("product");
		var selectedHtml = selected.html();

		var valueElement = prod.find(".item.value");
		valueElement.html(selectedHtml);
		valueElement.data("product", selectedData);
		
		this.Element.find(this.Options.BookButtonSelector).show();
		//jQuery(this.Options.BookButtonSelector).show();
	},

	ResetProduct: function() {
		var prod = this.Element.find(this.Options.ProductsSelector);
		var prodOptions = prod.find(this.Options.OptionsSelector);

		//JL 21/10/2010: Rather than display first item, display some info i.e. "Choose your room"
		//var first = prodOptions.find("div[rel]:first");
		//var firstData = first.parent().data("product");
		//var firstHtml = first.html();

		//var valueElement = prod.find(".item.value");
		//valueElement.html(firstHtml);
		//valueElement.data("product", firstData);

		if (this.ContainerID.match(".quickbook-experiences") || selectedType.match("experiences")) {
			var valueElement = prod.find(".item.value");
			valueElement.html("<img alt='' src='/images/gbp/icons/map-th-tasmania.gif'><strong>Choose from below</strong>");
		} else {
			var valueElement = prod.find(".item.value");
			valueElement.html("<img alt='' src='/images/gbp/icons/map-th-tasmania.gif'><strong>Choose your room</strong>");
		}
	},


	ResetProvider: function() {
		var prov = this.Element.find(this.Options.ProvidersSelector);
		var provOptions = prov.find(this.Options.OptionsSelector);
		var prod = this.Element.find(this.Options.ProductsSelector);

		var selectedDestination = this.Element.find(this.Options.DestinationsSelector).children().eq(0).data("destination");
		
		//JL 21/10/2010: Rather than display first item, display some info i.e. "Choose your hotel"
		//var first = provOptions.find("div[rel]:first");
		//var firstData = first.parent().data("provider");
		//var firstHtml = first.html();

		//var valueElement = prov.find(".item.value");
		//valueElement.html(firstHtml);
		//valueElement.data("provider", firstData);

		if (this.ContainerID.match(".quickbook-experiences") || selectedType.match("experiences")) {
			//todo: change message if there are no experiences
			var experienceProviders = provOptions.children();
			var valueElement = prov.find(".item.value");
			
			if (experienceProviders.length == 0 && selectedDestination && selectedDestination.ID > 0) {		
				valueElement.html("<img alt='' src='/images/gbp/icons/map-th-tasmania.gif'><strong>There is no availability at this time.</strong>");
				prod.hide();	
			}
			else{
				valueElement.html("<img alt='' src='/images/gbp/icons/map-th-tasmania.gif'><strong>Choose your experience</strong>");
				prod.show();
				
			}
		} else {
			var valueElement = prov.find(".item.value");
			valueElement.html("<img alt='' src='/images/gbp/icons/map-th-tasmania.gif'><strong>Choose your property</strong>");
		}
	}



});

