var jQuery_1_11_0 = jQuery_1_11_0 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		
		var slider = ($.fn.slider !== undefined),
			autosuggest = ($.fn.autosuggest !== undefined),
			routes = [
			    {pathname_pattern: /\/holiday-packages\/$/, hash_pattern: /^#!\/search\/(.*)$/, eventName: "loadHolidayPackages"},
			    {pathname_pattern: /\/best-deals\/$/, hash_pattern: /^#!\/search\/(.*)$/, eventName: "loadBestDeals"}
			],
			$sliderPrice = $("#filter-slider-price"),
			$sliderRating = $("#filter-slider-rating");

		function pjRegistry () {
			this.init.call(this);
		};
		pjRegistry.prototype = {
			init: function () {
				this.q = "";
				this.season = [];
				this.type = [];
				this.price = {"from": tConfig.min_price, "to": tConfig.max_price};
				this.rating = {"from": 1, "to": 5};
				this.view = "list";
				this.row_count = 10;
			},
			add: function (property, value) {
				if ($.inArray(property, ['season', 'type']) === -1) {
					return false;
				}
				
				if ($.inArray(value, this[property]) === -1) {
					this[property].push(value);
					
					$('<input>', {
						'type': "hidden",
						'name': property + "[]"
					}).val(value).prependTo(".form-filter");
				}
				
				return this;
			},
			remove: function (property, value) {
				if ($.inArray(property, ['season', 'type']) === -1) {
					return false;
				}
				
				this[property] = $.grep(this[property], function (val) {
					return val != value;
				});
				$(".form-filter").find("input[name='"+property+"[]'][value='"+value+"']").remove();
				
				return this;
			},
			set: function (property, from, to) {
				if ($.inArray(property, ['price', 'rating']) === -1) {
					return false;
				}
				
				this[property].from = from;
				this[property].to = to;
				
				$(".form-filter")
					.find("input[type='hidden'][name='"+property+"_from']").val(from)
					.end()
					.find("input[type='hidden'][name='"+property+"_to']").val(to);
				
				return this;
			},
			serialize: function () {
				return $(".form-filter").serialize();
			},
			clear: function () {
				this.init.call(this);
				$(".form-filter")
					.find("input[name='season[]'], input[name='type[]']").remove()
					.end()
					.find("input[name='q']").val("")
					.end()
					.find("input[type='hidden'][name='price_from']").val(this.price.from)
					.end()
					.find("input[type='hidden'][name='price_to']").val(this.price.to)
					.end()
					.find("input[type='hidden'][name='rating_from']").val(this.rating.from)
					.end()
					.find("input[type='hidden'][name='rating_to']").val(this.rating.to);
				
				return this;
			}
		};
		var registry = new pjRegistry();
		
		function hashBang(value) {
			if (value !== undefined && value.match(/^#!\//) !== null) {
				if (window.location.hash == value) {
					return false;
				}
				window.location.hash = value;
				return true;
			}
			
			return false;
		}
		
		function onHashChange() {
			var i, iCnt, m, 
				loc = window.location;
			for (i = 0, iCnt = routes.length; i < iCnt; i++) {
				m = loc.hash.match(routes[i].hash_pattern);
				if (m !== null && loc.pathname.match(routes[i].pathname_pattern) !== null) {
					$(window).trigger(routes[i].eventName, m.slice(1));
					break;
				}
			}
			if (m === null) {
				$(window).trigger("loadHolidayPackages", [""]);
			}
		}
		
		$(window).on("hashchange", function (e) {
	    	onHashChange.call(null);
	    }).on("loadHolidayPackages", this.container, function (e, query) {
			getHolidayPackages.call(null, query);
		}).on("loadBestDeals", this.container, function (e, query) {
			getBestDeals.call(null, query);
		});
		
		if (window.location.hash.length === 0) {
			//$(window).trigger("loadHolidayPackages", [""]);
		} else {
			onHashChange.call(null);
		}
		
		function search () {
			hashBang("#!/search/" + registry.serialize());
		}
		function getSearch (qs) {
			var jqXHR = $.get(tConfig.url + "search/" + qs);
			
			return jqXHR;
		}
		function getHolidayPackages (qs) {
			if (qs !== undefined && qs.length > 0) {
				qs = "?" + qs;
			}
			detachAutosuggest.call(null);
			
			var $results = $("#results");
			$results.html("");
			var jqXHR = getSearch.call(null, qs).done(function (data) {
				$results.html(data);
				attachAutosuggest.call(null);
				
				var $sliderPrice = $results.find("#filter-slider-price"),
					$sliderRating = $results.find("#filter-slider-rating");
				
				if ($sliderPrice.length > 0 && slider) {
					attachSliderPrice.call(null, $sliderPrice);
				}
				
				if ($sliderRating.length > 0 && slider) {
					attachSliderRating.call(null, $sliderRating);
				}
				
				if (qs.match(/view=map/) !== null) {
					if($("#map_canvas").length > 0)
					{
						getGoogleApi.call(null, qs);
					}
				}
				if($('#map_first_time').length > 0)
				{
					$(".form-filter")
						.find("input[name='view']").val('map')
						.end()
						.trigger("filter");
				}
			});
			
			return jqXHR;
		}
		function getBestDeals (qs) {
			if (qs !== undefined && qs.length > 0) {
				qs = "?" + qs;
			}
			qs = qs.indexOf("?") !== 0 ? qs + "?is_best_deal=1,2" : qs + "&is_best_deal=1,2";

			var jqXHR = getSearch.call(null, qs).done(function (data) {
				$("#results").html(data);
				
				if (qs.match(/view=map/) !== null) {
					getGoogleApi.call(null, qs);
				}
				if($('#map_first_time').length > 0)
				{
					$(".form-filter")
						.find("input[name='view']").val('map')
						.end()
						.trigger("filter");
				}
			});
			
			return jqXHR;
		}
		function getGoogleApi (qs) {
			qs += "&json=1"
			if (typeof window.initializeTravel == "undefined") {
				window.initializeTravel = function () {
					getSearch.call(null, qs).done(function (data) {
						drawMap.call(null, data.data, data.locale);
					})
				};
				$.getScript("http://maps.googleapis.com/maps/api/js?sensor=false&callback=initializeTravel");
			} else {
				getSearch.call(null, qs).done(function (data) {
					drawMap.call(null, data.data, data.locale);
				});
			}
		}
		function pjGoogleMaps() {
			this.map = null;
			this.bounds = new google.maps.LatLngBounds();
			this.cnt = 0;
			this.position = null;
		}
		pjGoogleMaps.prototype = {
			init: function () {
				this.map = new google.maps.Map(document.getElementById("map_canvas"), {
					zoom: 9,
					minZoom: 2,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				});
			},
			address: function (lat, lng, content) {
				var marker,
					self = this,
					position = new google.maps.LatLng(lat, lng);
				this.map.setCenter(position);
				this.bounds.extend(position);
				this.cnt += 1;
				this.position = position;
				marker = new google.maps.Marker({
					"map": this.map,
					"icon": "app/web/img/site/marker.png",
					"position": position
				});
				if (content !== null && content.length > 0 && content != "") {
					var infoWindow = new google.maps.InfoWindow({
						"content": content
					});
					google.maps.event.addListener(marker, "click", function() {
						infoWindow.open(self.map, marker);
					});
				}
			},
			fit: function () {
				if (this.cnt > 1) {
					//this.map.setZoom(8);
					this.map.fitBounds(this.bounds);
				} else if (this.cnt === 1) {
					this.map.setCenter(this.position);
					//this.map.setZoom(13);
				}
			}
		};
		function stripIt(str) {
			return str.replace(/\r\n|\n|\t/, '').replace("'", "\'");
		}
		function drawMap (data, locale) {
			var googleMaps = new pjGoogleMaps();
			googleMaps.init();
			
			var address_str, nights, address_arr, ypHtml, i, iCnt,
				ypAddressArr = [];
			for (i = 0, iCnt = data.length; i < iCnt; i++) {
				if (data[i].address_map === null || parseInt(data[i].address_map, 10) !== 1) {
					continue;
				}
				if (data[i].lat === null || data[i].lng === null || data[i].lat.length === 0 || data[i].lng.length === 0)
				{
					continue;
				}
				address_str = '';
				nights = null;
				if (data[i].listing_nights !== null && data[i].listing_nights.length !== 0)
				{
					nights = data[i].listing_nights;
					if (data[i].listing_nights > 1) {
						nights += ' ' + locale.nights;
					} else {
						nights += ' ' + locale.night;
					}
				}

				address_arr = [data[i].address_city, data[i].address_state, data[i].country_title];
				if (data[i].address_content === null || data[i].address_content.length === 0)
				{
					address_str = address_arr.join(", ");
				} else {
					address_str = data[i].address_content + ',<br/>' + address_arr.join(", ");
				}

				ypHtml = [];
				
				ypHtml.push('<div class="vpl-info-mapview">');
				ypHtml.push('<label class="vpl-map-title">' + stripIt(data[i].listing_title) + '</label>');
				
				if (address_str !== '')
				{
					ypHtml.push('<label class="vpl-map-address">' + stripIt(address_str) + '</label>');
				}
				ypHtml.push('<label class="vpl-map-price">' + stripIt(locale.price) + ": <span>" + stripIt(data[i].price) + '</span></label>');
				
				if (nights !== null && data[i].flight_included == 'T')
				{
					ypHtml.push('<label class="vpl-map-nights-flight">' + stripIt(nights) + ', ' + stripIt(locale.flight) + '</label>');
				} else if (nights !== null) {
					ypHtml.push('<label class="vpl-map-nights-flight">' + stripIt(nights) + '</label>');
				} else if (data[i].flight_included == 'T') {
					ypHtml.push('<label class="vpl-map-nights-flight">' + stripIt(locale.flight) + '</label>');
				}
				ypHtml.push('<a class="vpl-map-view-detail" href="' + data[i].url + '">' + stripIt(locale.details) + '</a>');
				ypHtml.push('<\/div>');

				ypAddressArr.push({
					"lat": parseFloat(data[i].lat), 
					"lng": parseFloat(data[i].lng), 
					"html": ypHtml.join("")
				});
			}
			if (ypAddressArr.length > 0) {
				for (i = 0, iCnt = ypAddressArr.length; i < iCnt; i++) {
					googleMaps.address(ypAddressArr[i].lat, ypAddressArr[i].lng, ypAddressArr[i].html);
				}
				googleMaps.fit();
			}
		}
		
		function formatCurrency (price, currency) {
			var format = '---';
			price = price.toFixed(2);
			switch (currency)
			{
				case 'USD':
					format = "$" + price;
					break;
				case 'GBP':
					format = "&pound;" + price;
					break;
				case 'EUR':
					format = "&euro;" + price;
					break;
				case 'JPY':
					format = "&yen;" + price;
					break;
				case 'AUD':
				case 'CAD':
				case 'NZD':
				case 'CHF':
				case 'HKD':
				case 'SGD':
				case 'SEK':
				case 'DKK':
				case 'PLN':
					format = price + currency;
					break;
				case 'NOK':
				case 'HUF':
				case 'CZK':
				case 'ILS':
				case 'MXN':
					format = currency + price;
					break;
				default:
					format = price + $currency;
					break;
			}
			
			return format;
		}
		
		function attachSliderPrice ($slider) {
			var currency = $("#vpl_filter_price").data('currency');
			$slider.slider({
				range: true,
				min: tConfig.min_price,
				max: tConfig.max_price,
				step: 10,
				values: [parseInt($slider.data("price_from"), 10), parseInt($slider.data("price_to"), 10)],
				slide: function (event, ui) {
					$("#vpl_filter_price").html(formatCurrency(parseInt(ui.values[0], 10), currency) + ' - ' + formatCurrency(parseInt(ui.values[1], 10), currency));
				},
				stop: function (event, ui) {
					var from = parseInt(ui.values[0], 10),
						to = parseInt(ui.values[1], 10);
					registry.set("price", from, to);
					var $old = $(".filter-selected").find("a.filter-content-item-active[data-section='price']"),
						$a = $(['<a href="#" class="filter-content-item filter-content-item-active" data-section="price">', formatCurrency(from, currency), ' - ', formatCurrency(to, currency), ' </a>'].join(""));
					if ($old.length > 0) {
						$old.replaceWith($a);
					} else {
						//$a.appendTo(".filter-selected");
						$a.insertBefore(".filter-clear");
					}
					clear();
				}
			});
		}
		function detachSliderPrice ($slider) {
			$slider.slider("destroy");
		}
		function attachSliderRating ($slider) {
			$slider.slider({
				range: true,
				min: 1,
				max: 5,
				values: [parseInt($slider.data("rating_from"), 10), parseInt($slider.data("rating_to"), 10)],
				//slide: function(event, ui) {},
				stop: function(event, ui) {
					var from = parseInt(ui.values[0], 10),
						to = parseInt(ui.values[1], 10);
					registry.set("rating", from, to);
					var $old = $(".filter-selected").find("a.filter-content-item-active[data-section='rating']"),
						$a = $(['<a href="#" class="filter-content-item filter-content-item-active" data-section="rating">', from, ' stars - ', to, ' stars</a>'].join(""));
					if ($old.length > 0) {
						$old.replaceWith($a);
					} else {
						//$a.appendTo(".filter-selected");
						$a.insertBefore(".filter-clear");
					}
					clear();
				}
			});
		}
		function detachSliderRating ($slider) {
			$slider.slider("destroy");
		}
	
		if ($sliderPrice.length > 0 && slider) {
			attachSliderPrice.call(null, $sliderPrice);
		}
		
		if ($sliderRating.length > 0 && slider) {
			attachSliderRating.call(null, $sliderRating);
		}
		
		function clear() {
			var $el = $(".filter-clear");
			if ($el.length > 0) {
				if ($(".filter-content-item-active").length > 0) {
					$el.show();
				} else {
					$el.hide();
				}
			}
		}
		
		function attachAutosuggest() {
			$("input[name='q']").autosuggest({
				url: tConfig.url + "location/"
			});
		}
		function detachAutosuggest() {
			$("input[name='q']").autosuggest('destroy');
		}
		
		if (autosuggest) {
			attachAutosuggest.call(null);
		}
		
		$(document).on("click", ".filter-control-item", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				selector = "." + $this.data("content");
			
			$(".filter-control-item").not($this).removeClass("filter-control-item-active");
			$(".filter-content").not(selector).hide();
			$(selector).toggle();
			if ($(selector).is(":visible")) {
				$this.addClass("filter-control-item-active");
			} else {
				$this.removeClass("filter-control-item-active");
			}
			return false;
		}).on("click", ".filter-content-item-disabled", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}).on("click", ".filter-content-item:not(.filter-content-item-active):not(.filter-content-item-disabled)", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this);
			//$this.clone().addClass("filter-content-item-active").appendTo(".filter-selected");
			$this.clone().addClass("filter-content-item-active").insertBefore(".filter-clear");
			clear();
			$this.addClass("filter-content-item-disabled");
			registry.add($this.data("section"), $this.data("value"));
			return false;
		}).on("click", ".filter-content-item-active", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				section = $this.data("section"),
				value = $this.data("value");
			registry.remove(section, value);
			$(".filter-content-" + section)
				.find("a.filter-content-item-disabled[data-section='"+section+"'][data-value='"+value+"']")
				.removeClass("filter-content-item-disabled");
			$this.remove();
			clear();
			
			switch (section) {
			case 'q':
				registry.q = "";
				$(".form-filter").find("input[name='q']").val("");
				break;
			case 'price':
				registry.set(section, tConfig.min_price, tConfig.max_price);
				break;
			case 'rating':
				registry.set(section, 1, 5);
				break;
			}
			return false;
		}).on("click", ".filter-clear", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			registry.clear();
			$(".form-filter").trigger("filter");
			return false;
		}).on("filter", ".form-filter", function (e) {
			search.call(null);
		}).on("submit", "#filter-home", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			window.location.href = tConfig.url + "holiday-packages/#!/search/" + registry.serialize();
			return false;
		}).on("submit", "#filter-packages", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).trigger("filter");
			return false;
		}).on("mouseenter", ".list-item", function (e) {
			$(this).addClass("list-hover");
		}).on("mouseleave", ".list-item", function (e) {
			$(this).removeClass("list-hover");
		}).on("change", "#per-page", function (e) {
			$(".form-filter")
			.find("input[name='row_count']").val($(this).find("option:selected").val())
			.end()
			.trigger("filter");
		}).on("click", "a.viewing-mode", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(".form-filter")
				.find("input[name='view']").val($(this).data("view"))
				.end()
				.trigger("filter");
			return false;
		}).ajaxStart(function () {
			$("#preloader").show();
		}).ajaxStop(function () {
			$("#preloader").hide();
		});
	});
})(jQuery_1_11_0);