var webserviceAPI = 'webservice';
var hash = '';
var mousePos;
var $_GET = {};


/* Datepicker */
var selections = {};


/* Save get variables */
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
	function decode(s) {
	    return decodeURIComponent(s.split("+").join(" "));
	}
	$_GET[decode(arguments[1])] = decode(arguments[2]);
});


$(document).ready(function(){

	/* Global */
	$(document).mousemove(function(e) {
		mousePos = e;
	});
	$("#main").css({"min-height":($(window).height()-$("header").outerHeight()-$("footer").outerHeight() - 60)+"px"});


	$.expr[':'].parents = function(a,i,m){
	    return jQuery(a).parents(m[3]).length < 1;
	};
	
	
	/* Masonry Widgets */
	if($(".booknow").length != 0) {
		$.Mason.prototype._reLayout = function( callback ) {
			var freeCols = this.cols;
			if ( this.options.cornerStampSelector ) {
				var $cornerStamp = this.element.find( this.options.cornerStampSelector );
				if($cornerStamp.offset().left != null) {
					var cornerStampX = $cornerStamp.offset().left - ( this.element.offset().left + this.offset.x + parseInt($cornerStamp.css('marginLeft')) );
					freeCols = Math.floor( cornerStampX / this.columnWidth );			
				}
	
			}
			var i = this.cols;
			this.colYs = [];
			while (i--) {
				this.colYs.push( this.offset.y );
			}
			for ( i = freeCols; i < this.cols; i++ ) {
				this.colYs[i] = this.offset.y + $cornerStamp.outerHeight(true);
			}
			this.layout( this.$bricks, callback );
		};
		$('#masonry').masonry({
			isAnimated: true,
			cornerStampSelector: '.booknow',
			itemSelector: '.box:not(.hide, .booknow)',
			columnWidth: 1
		});	
	    $(window).scroll(function () {
	    	$(".oldie #booking_gadget").css({'position':'absolute', 'top': $(this).scrollTop() + 50 + "px"});			
			if($(window).scrollTop() > $(".booknow").offset().top + $(".booknow .p-blue_bg").height()) {
				$("#booking_gadget a").stop().animate({"right":"0px", opacity: 1}, 100);
			} else {
				$("#booking_gadget a").stop().animate({"right":"-88px", opacity: 0}, 100);
			}
	    });
		$("#booking_gadget a").click(function(e){
			e.preventDefault();
			$('html, body').animate({scrollTop: $(".booknow").offset().top}, 400);
		})
	} else {
		$('#masonry').masonry({
			isAnimated: false,
			itemSelector: '.box:not(.hide, .booknow)',
			columnWidth: 1
		});
	}



    /* Focus inputs */
    function inputDefaultValue() {
	    $("input.text").each(function(){
	    	var that = $(this);
	    	var default_value = '';
	    	if(that.val() != "") {
	    		default_value = that.val();
	    	} else {
	    		default_value = that.attr("data-default");
	    	}
		    that.val(default_value).focus(function(){
		        var newValue = that.val();
		        if(that.val() == default_value){
		            that.attr('value', '');
		        } else {
		            that.val(newValue);
		        }
		        that.addClass("focus");
		    }).blur(function(){
		        var newValue = that.val();
		        if(that.val() == ''){
		            that.attr('value', default_value);
		        } else {
		            that.val(newValue);
		        }
		        that.removeClass("focus");
		    });
	    });    
    }
    inputDefaultValue();

    
    
    /* Hover inputs, button and link */
    $("input, button, .button, a").hover(
    	function(){
	    	$(this).addClass("hover");
	    },function(){
	    	$(this).removeClass("hover");
	    }
    );
    


    /* Tooltips */
	$("#timeline_panel [title]").tooltip({
		effect: 'fade',
		fadeOutSpeed: 100,
		predelay: 600,
		offset: [10, 2],
		onBeforeShow: function(){
			setTimeout(function(){
				$(".tooltip").css({
				    left:(mousePos.pageX - $.tools.tooltip.conf.offset[1] + 10),
				    top:(mousePos.pageY - $.tools.tooltip.conf.offset[0] - 40)
				});
			}, 10);
		}
	}).dynamic({
		bottom: { direction: 'down' } 
	}).mousemove(function(evt) {
		$(".tooltip").css({
		    left:(evt.pageX - $.tools.tooltip.conf.offset[1] + 10),
		    top:(evt.pageY - $.tools.tooltip.conf.offset[0] - 40)
		});
	});

	

	/* Dropdown styling */
	$('select').selectmenu({
		style:'dropdown',
		menuWidth: 240,
		maxHeight: 500,
		positionOptions: {
			collision: 'none'
		},
		open: function(){
			$(".ui-selectmenu-open").css("top", "-=24px");
		}
	});
	
	
	
	/* Homapage Slideshow */
    $("#homepage_slider").noiceSlideshow({ 
        slideshow_width: 620,
        slideshow_height: 460,
        slideshow_nav_pages: true,
        slideshow_nav_pages_tooltip: false,
        slideshow_nav_prev_next: true,
        item_timer: 7000,
        item_trans_dir: "none",
        item_trans_opt: "none",
        slices_vertical: 1,
        slices_horizontal: 1,
        slices_trans: "none",
        slices_trans_dir: "none",
        slices_trans_opt: "none",
        slices_trans_speed: 1000,
        slices_trans_delay: 70      
    });
    
	

	/* Datepicker & Booking Validation */	
	$.datepicker.setDefaults({
		beforeShowDay: beforeShowDayHandler,
		showOtherMonths: true
	});

	$('#departure_input').datepicker({
		altField: $(this).next(),
		altFormat: "yy-mm-dd",
		dateFormat: "'Leaving:' D, d M yy",
		rangeSelect: true,
		rangeSeparator: 'to',
		beforeShow: beforeShowHandler,
		onSelect: onSelectHandler
	});
	$('#return_input').datepicker({
		altField: $(this).next(),
		altFormat: "yy-mm-dd",
		dateFormat: "'Returning:' D, d M yy",
		rangeSelect: true,
		rangeSeparator: 'to',
		beforeShow: beforeShowHandler,
		onSelect: onSelectHandler
	});
	$('.datepicker:not(.range)').datepicker({
		altField: $(this).next(),
		altFormat: "yy-mm-dd",
		dateFormat: "'Leaving:' D, d M yy",
		beforeShow: beforeShowHandler,
		onSelect: onSelectHandler
	});

	function beforeShowHandler(input) {
		daysToEnable = eval("daysToEnable_"+$("#"+input.id).next().attr("id"));
		if(input.className.indexOf("departure") != -1 && input.className.indexOf("range") != -1) {
			$("#ui-datepicker-div td").die();
			var selectedDate = $("#departure_input").datepicker("getDate");
			if (selectedDate != null) { 
				$('#return_input').datepicker('option', 'minDate', selectedDate);//
			}
		} else if(input.className.indexOf("return") != -1 && input.className.indexOf("range") != -1) {
			$("#ui-datepicker-div td").live({
				mouseenter: function() {
                    $(this).parent().addClass("finalRow");
                    $(".finalRow").prevAll().find("td:not(.ui-datepicker-unselectable)").addClass("highlight");
                    $(this).prevAll("td:not(.ui-datepicker-unselectable)").addClass("highlight");
				},
				mouseleave: function() {
                    $(this).parent().removeClass("finalRow");
                    $("#ui-datepicker-div td").removeClass("highlight");
				}
			});
			var selectedDate = $("#departure_input").datepicker("getDate");
			if (selectedDate != null) { 
				$('#return_input').datepicker('option', 'minDate', selectedDate);
			}
		}
	}

	function beforeShowDayHandler(date) {	
		var dateString = $.datepicker.formatDate('yy-mm-dd', date);
		if ($.inArray(dateString, daysToEnable) != -1) {
			return [true];
		}
		return [false];
	}
	
	function onSelectHandler(input, inst) {
		$("#booking_widget_form, #booking_form").validate().element(this);
		var dateString = inst.selectedYear+"-"+(inst.selectedMonth+1)+"-"+inst.selectedDay;
		$("#"+inst.id).next().val(dateString);
		inSelections(inst.id, dateString);
		if($("div.error:visible").length == 0) {
			$("#booking_form [type=submit]").removeClass("disabled");
		} else {
			$("#booking_form [type=submit]").addClass("disabled");
		}
	}

	function updateDropdowns(thisform, callback){
		if($("div.error:visible").length == 0) {
			$("#booking_form [type=submit]").removeClass("disabled");
		} else {
			$("#booking_form [type=submit]").addClass("disabled");
		}
		getOrigins(thisform, function(){
			getDestinations(thisform, function(){
				callback();
			});
		});
	}
	
	function buildSelectOptions(options, defaultValue) {
		var output = '<option selected="selected" value="">'+defaultValue+'</option>';
		for(var i = 0; i < options.length; i++){
			output += '<optgroup label="'+options[i].name+'">';
			for(var j = 0; j < options[i].data.length; j++) {
				output += '<option value="'+options[i].data[j].value+'">'+options[i].data[j].name+'</option>';
			}
			output += '</optgroup>';
		}
		return output;
	}

	function getSelectOptions(webservice, thisform, input, defaultValue, callback) {
		var selectLen = thisform.find(input).length;
		if(selectLen != -1) {
			thisform.find(input).each(function(){
				var current_id = $(this).attr("id");
				if($.param(selections).indexOf(current_id) == -1) {
					var params = $.param(selections);
					var output = '<option selected="selected">loading...</option>';
					$("#"+current_id).html(output);
					$('#'+current_id+' option:eq(0)').attr('selected', 'selected');
					$("select").peek("selectmenu");
					$.ajax({
						url: webserviceAPI+"/"+webservice,
						data: params,
						success: function(response){
							var obj = jQuery.parseJSON(response);
							var output = buildSelectOptions(obj, defaultValue);
							$("#"+current_id).html(output);
							$('#'+current_id+' option:eq(0)').attr('selected', 'selected');
							$("select").peek("selectmenu");
							$('#'+current_id+' option:eq(0)').attr('disabled', 'disabled').addClass("disabled");
							$("select").peek("selectmenu");
							callback();							
						}
					});
				} else {
					callback();
				}
			});
		} else {
			callback();
		}
	}

	function getServices(thisform, callback){
		getSelectOptions("getService", thisform, "select.servicename", "All services", callback);
	}

	function getOrigins(thisform, callback){
		getSelectOptions("getOrigin", thisform, "select.origin", "From:", callback);
	}
	
	function getDestinations(thisform, callback){
		getSelectOptions("getDestination", thisform, "select.destination", "To:", callback);
	}

	function getDepartures(thisform, callback) {
		var input = "input.departure";
		var selectLen = thisform.find(input).length;
		if(selectLen != -1) {
			thisform.find(input).each(function(e){
				var current_id = $(this).attr("id");
				if($.param(selections).indexOf(current_id) == -1) {
					var params = $.param(selections);
					$.ajax({
						url: webserviceAPI+"/getDepartureDates",
						data: params,
						success: function(response){
							daysToEnable = jQuery.parseJSON(response);
							$("#"+current_id).datepicker("refresh");
							if(e+1 == selectLen) {
								callback();
							}
						}
					});
				} else {
					callback();
				}
			});
		} else {
			callback();
		}
	}
	
	function inSelections(inputName, inputValue) {
		if($.param(selections).indexOf(inputName) == -1){
			selections[inputName] = inputValue;
		} else {
			selections = {};
			selections[inputName] = inputValue;

			$("[name='"+inputName+"']").parents(".leg").find('select').each(function(){
				if($(this).attr("name") != inputName) {
					$(this).selectmenu("value", "");
				}
			});
		}
	}

	$.validator.setDefaults({
		focusCleanup: true,
		errorPlacement: function(error, element) {},
		highlight: function(element, errorClass, validClass) {
			$(element).addClass(errorClass).removeClass(validClass);
			$(element).parent().find(".message div").addClass(errorClass).removeClass(validClass);

			if(this.numberOfInvalids() == 0) {
				$("#booking_form [type=submit]").removeClass("disabled");
			} else {
				$("#booking_form [type=submit]").addClass("disabled");
			}
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).removeClass(errorClass).addClass(validClass);
			$(element).parent().find(".message div").removeClass(errorClass).addClass(validClass);

			if(this.numberOfInvalids() == 0) {
				$("#booking_form [type=submit]").removeClass("disabled");
			} else {
				$("#booking_form [type=submit]").addClass("disabled");
			}
		}
	});
	
		
    $(".booking_form select").change(function(){
    	$("#booking_widget_form, #booking_form").validate().element(this);
    	var that = $(this);
    	var inputName = $(this).attr("name");
    	var inputValue = $(this).find("option:selected").val();
    	
		if(inputName.indexOf("servicename") != -1 && inputValue.indexOf("CapitalConnection") != -1) {
			that.parents(".leg").find("select.origin").parent().hide().prev().hide();
			that.parents(".leg").find("select.destination").parent().hide().prev().hide();
			that.parents(".leg").find(".departure").parent().hide().prev().hide();
			$(".CapitalConnection_hide").hide();
			that.parents(".leg").find(".CapitalConnection_show").show();
			$(".remove_leg").hide();
			return false;
		} else {
			that.parents(".leg").find("select.origin").parent().show().prev().show();
			that.parents(".leg").find("select.destination").parent().show().prev().show();
			that.parents(".leg").find(".departure").parent().show().prev().show();
			$(".CapitalConnection_hide").show();
			that.parents(".leg").find(".CapitalConnection_show").hide();
			$(".remove_leg").show();
			init_legs();
		}
    	
		inSelections(inputName, inputValue);

		updateDropdowns($(this).parents(".leg"), function(){
			if(inputName.indexOf("servicename") != -1 && inputValue.indexOf("SR") != -1) {
				that.parents(".leg").find("select.origin, select.destination").attr("disabled", true).addClass("disabled").peek("selectmenu");
				$("#return_input").attr("disabled", true).addClass("disabled");
				return false;
			} else {
				that.parents(".leg").find("select.origin, select.destination").attr("disabled", false).removeClass("disabled").peek("selectmenu");
				$("#return_input").attr("disabled", false).removeClass("disabled");
			}
		});
    });
	
	/* Widget booking form */
	$("#booking_widget_form").validate({
		ignore: false,
		rules: {
			'origin': {
				required: true
			},
			'destination': {
				required: true
			},
			'departure': {
				required: true
			},
			'input_service_adults': {
				 required: true
			}
		},
		invalidHandler: function(form, validator) {
			this.submit();
		},
		submitHandler: function(form) {
			$("#booking_widget_form [type=submit]").attr('disabled', 'disabled').removeClass("disabled").addClass("loading").find("span").html("&nbsp;&nbsp;&nbsp;");
			$(form).append('<input type="hidden" name="booking" value="valid">');
			setTimeout(function(){form.submit();}, 1000);
		}
	});


	/* Guided booking form */
	$("#booking_form").validate({
		ignore: '.leg:hidden .required:hidden',
		rules: {
			'origin': {
				required: true
			},
			'destination': {
				required: true
			},
			'departure_input': {
				required: true
			},
			'input_service_adults': {
				 required: true
			}
		},
		submitHandler: function(form) {
			$("#booking_form [type=submit]").attr('disabled', 'disabled').removeClass("disabled").addClass("loading").find("span").html("&nbsp;&nbsp;&nbsp;");
			$(form).append('<input type="hidden" name="booking" value="valid">');
			setTimeout(function(){form.submit();}, 1000);
		}
	});

	/* Add & remove Legs */
	$("#add_leg a").unbind("click").bind("click", function(e){
		e.preventDefault();
		$(".leg:not(:visible):first").show();
		init_legs();
	});

	$(".remove_leg").unbind("click").bind("click", function(e){
		e.preventDefault();
		var remove_confirm = confirm("Are you sure?");
		if (remove_confirm == true) {
			$(this).closest(".leg").hide();
			init_legs();
		}
	});
	
	function init_legs(){
		var legs = $(".leg:visible").length;
		if(legs > 1) {
			$("#return_date").hide().find("input").val("");
		} else {
			$("#return_date").show();
		}
		if(legs == 3) {
			$("#add_leg").hide();
		} else {
			$("#add_leg").show();
		}
		
		$(".leg:visible .remove_leg").hide();
		$(".leg:visible:last .remove_leg").show();
	}

	function init_booking() {
		var url_path = window.location.pathname;
		if(url_path.indexOf("tranzalpine") != -1) {
			$('#servicename option[value="TranzAlpine"]').attr('selected', 'selected');
		} else if(url_path.indexOf("coastal-pacific") != -1) {
			$('#servicename option[value="Coastal Pacific"]').attr('selected', 'selected');
		} else if(url_path.indexOf("overlander") != -1) {
			$('#servicename option[value="Overlander"]').attr('selected', 'selected');
		}

		if($_GET["servicename"]) {

			if($_GET["servicename"].indexOf("SR") != -1) {
				$(".leg:visible").find("select.origin, select.destination").attr("disabled", true).addClass("disabled").peek("selectmenu");
				$("#return_input").attr("disabled", true).addClass("disabled");
			} 
		
			$("#servicename").val($_GET["servicename"]);
			inSelections("servicename", $_GET["servicename"]);
		}
		if($_GET["origin"]) {
			$("#origin").val($_GET["origin"]);
			inSelections("origin", $_GET["origin"]);
		}
		if($_GET["destination"]) {
			$("#destination").val($_GET["destination"]);
			inSelections("destination", $_GET["destination"]);
		}
		if($_GET["departure"]) {
			var departureDate = $.datepicker.parseDate("yy-mm-dd",  $_GET["departure"]);
			$('#departure_input').datepicker("setDate", departureDate).next().val($_GET["departure"]);
		}
		if($_GET["return"]) {
			var returnDate = $.datepicker.parseDate("yy-mm-dd",  $_GET["return"]);
			$('#return_input').datepicker("setDate", returnDate).next().val($_GET["return"]);
		}
		if($_GET["input_service_adults"]) {
			$('#input_service_adults').val($_GET["input_service_adults"]);
		}
		if($_GET["input_service_children"]) {
			$('#input_service_children').val($_GET["input_service_children"]);
		}
		if($_GET["input_service_infants"]) {
			$('#input_service_infants').val($_GET["input_service_infants"]);
		}
		
		
		if(($_GET["servicename"] && $_GET["servicename"] != "") || ($_GET["origin"] && $_GET["origin"] != "") || ($_GET["destination"] && $_GET["destination"] != "")) {
			updateDropdowns($(".booking_form .leg:visible"), function(){});
		}
		
		$("select").peek("selectmenu");
		
		init_legs();
	}

	
    
    
	$("#newsletter_form").validate({
		//debug: true,
		rules: {
			'email': {
				required: true,
				email: true
			}
		},
		invalidHandler: function(form, validator) {
			$("#newsletter_form label").text("Please check your address:");
		},
		submitHandler: function(form) {
			var params = $(form).serialize();
			// .log(params);
			$.ajax({
				type: "GET",
				url: webserviceAPI+"/registerEmail",
				data: params,
				success: function(response){
					var obj = jQuery.parseJSON(response);
					//console.log(response);
					if(obj.code == "exists") {
						$("#newsletter_form").html('You are already on our newsletter list.');
					} else if(obj.code == "ok") {
						$("#newsletter_form").html('Thanks for signing up for our newsletter.');
					} else {
						$("#newsletter_form").html('There was an error. Please try again later.');
					}
				}
			});
			
		}
	});
    

	/* Timeline */
	if ($("#timeline_scroller").length != 0) {	
		var items = new Array();
		var currentItem = 0;
		var itemsWidth = 0;
		var fastDuration = 1000;
		var itemDuration = 3000;
		var autoplayDelay = 6000;
		var timerPause = false;
		var playReverse = false;
		var timelineWidth = $("#timeline").width();
		var itemWidth = timelineWidth / ($("#timeline_content .item").length - 1);
		var itemsLeftMargin = Math.floor((($(window).width() / 2)) - ($("header .wrap").width() / 2));
		var timelineFeaturedItems = $("#timeline_panel .featured .item").length;
		var timelineFeaturedItemWidth = $("#timeline_panel .featured .item:first .icon").width();
		var timelineFeaturedItemMarginLeft = timelineFeaturedItemWidth / 2;
		var timelineStopoffItems = $("#timeline_panel .stopoffs .item").length;
		var timelineStopoffItemWidth = $("#timeline_panel .stopoffs .item:first .icon").width();
		var timelineStopoffItemMarginLeft = timelineStopoffItemWidth / 2;
		
		$("#timeline_content .item").each(function(e, i){
			items.push($(this).outerWidth());
			$(this).css({"width":$(this).outerWidth()+"px"});
		});
		$.each(items,function(e) {
	    	itemsWidth += this;
		});
	
		$("#timeline_panel .featured .item").each(function(e){
			var leftPos = (calcItemLeftPos(e, items) / (itemsWidth - 906)  ) * 906;
			$(this).css({"left":(leftPos + 17)+"px"});
		});
		
		$("#timeline_panel .stopoffs .item").each(function(){
			$(this).css({"margin-left":timelineStopoffItemMarginLeft+"px"})
	    	timelineStopoffItemMarginLeft += (timelineWidth - timelineStopoffItemWidth) / (timelineStopoffItems - 1);
		});

		$("#timeline_content .items").css({"width":(itemsWidth + 40)+"px","margin-left":itemsLeftMargin+"px", "padding-right":itemsLeftMargin+"px"});		
		$("#timeline_content .items .item:first").addClass("active");
		$("#timeline_content .items").addClass("active", fastDuration);
		$("#timeline_panel").addClass("active", fastDuration);
	
	
		$("#timeline_scroller, #timeline_panel").mouseenter(function(){
			timerPause = true;
		}).mouseleave(function(){
			timerPause = false;
		});
	
		
		$("#timeline_panel .prev_item").click(function(e){
			e.preventDefault();
			playReverse = true;
			playPrevItem();
		});
		$("#timeline_panel .next_item").click(function(e){
			e.preventDefault();
			playReverse = false;
			playNextItem();
		});
		
		
		$("[data-timeline-step]").live({
	        mouseenter:
	           function(){
					$(this).addClass("hover", fastDuration);
	           },
	        mouseleave:
	           function(){
					$(this).removeClass("hover", fastDuration);
	           }
	       }
		).click(function(e){
			e.preventDefault();
			var next_item = parseFloat($(this).attr("data-timeline-step"));
			if($(this).hasClass("icon") || $(this).hasClass("item")) {
				next_item--
			} 
			timerPause = true;
			currentItem = next_item;
			animateToItem(currentItem);
		});
	
		var scrollbar = $("#slider").slider({
			animate: itemDuration,
			min: 0,
			max: $("#timeline_content .items").width() - $("#filter").width(),
			change: handleSliderChange,
			slide: handleSliderSlide
		});
		
		setInterval(updateSlider, 10);
		setInterval(autoplaySlider, autoplayDelay);
	}
	
	
	function calcItemLeftPos(item, arr){
		var leftItemPos = 0;
		for(i = 0; i < item; i++) {
			leftItemPos += arr[i];
		}
		return leftItemPos;
	}

	function animateToItem(i){
		var scrollToItemPos = calcItemLeftPos(i, items);
		$("#timeline_content .items .item").removeClass("active", fastDuration);
		$("#timeline_content .items .item:eq("+i+")").addClass("active", fastDuration);
		$("#slider").slider("value", scrollToItemPos);
	}

	function playPrevItem(){
		if(currentItem > 0) {
			currentItem--;
		} 
		if(currentItem == 0) {
			playReverse = false;
		}
		animateToItem(currentItem);
	}
	
	function playNextItem(){
		if(currentItem + 1 < items.length) {
			currentItem++;
		} 
		if(currentItem + 1 == items.length) {
			playReverse = true;
		}
		animateToItem(currentItem);
	}	
	
	function handleSliderChange(e, ui) {
	    $("#timeline_content").stop().animate({scrollLeft: ui.value}, scrollbar.slider("option", "animate"));
	}
	
	function handleSliderSlide(e, ui) {
	    $("#timeline_content").stop().prop({scrollLeft: ui.value});
	}

	function updateSlider() {
		var offset = $('#timeline_content .items').offset();
		var sliderOffset = - (offset.left - itemsLeftMargin);
		isVisible(sliderOffset);
	
		if($(".ui-slider-handle").is(':animated')) return;

		if($(".ui-slider-handle").css("left") == "100%"){
			currentItem = items.length - 1;
		} else {
			$.each(items, function(e){
				var itemOffset = calcItemLeftPos(e, items);
				if(sliderOffset >= itemOffset) {
					currentItem = e;
					return
				}
			});
		}		
	}
	
	function autoplaySlider() {
		if(timerPause || $(".ui-slider-handle").is(':animated')) return;
		if(playReverse == true) {
			playPrevItem();
		} else {
			playNextItem();
		}
	}
	
	function isVisible(value){
		var scrollLeftPos = value;
		var scrollRightPos = scrollLeftPos + 940;
		$("#timeline_content .item").each(function(e){
			var eleLeft = calcItemLeftPos(e, items);
			var eleRight = eleLeft + items[e];
			if(eleRight > scrollLeftPos && eleLeft < scrollRightPos) {
				$(this).addClass("visible");
			} else {
				$(this).removeClass("visible");
			}
		});
	}	



	/* Image gallery */	
	function init_widgets() {
		$(".gallery_holder a.prev, .gallery_holder a.next").click(function(e){
			e.preventDefault();	
		});
		
		$(".scrollable").scrollable({
			items: ".items",
			prev: ".prev",
			next: ".next",
			onSeek: function(e){
				if(this.getIndex()+1 == 1) {
					$(this).parent().find(".prev").addClass("disabled");
				} else {
					$(this).parent().find(".remove").removeClass("disabled");
				}
				
				if(this.getIndex()+1 == this.getItems().length) {
					$(this).parent().find(".next").addClass("disabled");
				} else {
					$(this).parent().find(".next").removeClass("disabled");
				}
			}
		});
		
		$('#masonry').masonry('reload');
	}
	
	


	/* Search form */
	
	if($_GET["Search"]){
		$("#search_button").click(function(){
			$("#main #SearchForm_SearchForm_action_results").trigger("click");
		});
		$("#main #SearchForm_SearchForm_Search").attr("value", $_GET["Search"]);
		$("#main #SearchForm_SearchForm_Search").attr("default-value", $_GET["Search"]);

		var results_total = parseFloat($(".results_total").text());
		
		if($_GET["start"]){
			var from = parseFloat($_GET["start"]) + 1;
			var to = from + 9;
			if(results_total < to) {
				to = from + to - results_total - 1;
			}
			$(".page_from").text(from);
			$(".page_to").text(to);
		} else {
			var from = 1;
			var to = from + 9;
			if(results_total < to) {
				to = results_total;
			}
			$(".page_from").text(from);
			$(".page_to").text(to);
		}
		
	}


	/* Tripexplorer */	
	
	/* More / Less Button */
	$("#trip_explorer .group").each(function(){
		var rightWidth = $(this).width() - $(this).find(".left").outerWidth(true);
		$(this).find(".right").css({"width":rightWidth+"px"});
	});
	
	$("#trip_explorer .group").each(function(){
		var expanded_height = $(this).find(".right").height();
		var collapse_height = $(this).find(".item:first").outerHeight(true);
		if($(this).find(".right").height() > $(this).find(".item:first").outerHeight(true)) {
			$(this).find(".right").css({"height":"36px", "overflow":"hidden"}).prepend('<a href="#" class="more button" data-collapse_height="'+collapse_height+'" data-expanded_height="'+expanded_height+'">More <span class="icon">&#x25BC;</span></a>');
		}
	});

	
	$("#trip_explorer .more").toggle(function(e){
		e.preventDefault();
		var new_height = $(this).attr("data-expanded_height");
		$(this).html('Less <span class="icon">&#x25B2;</span>');
		$(this).parent().animate({
			height: new_height
		});
	}, function(e){	
		e.preventDefault();
		var new_height = $(this).attr("data-collapse_height");
		$(this).html('More <span class="icon">&#x25BC;</span>');
		$(this).parent().animate({
			height: new_height
		});
	});


	/* URL Segment */
	$('#trip_explorer a.item').live( 'click', function(e){
		e.preventDefault();
		$(this).toggleClass("active");
		$("#trip_explorer .group").each(function(e){
			var url = $(this).find("a.item:first").attr("href");
			var url = url.split("?");
			var url = url[1].split("=");
			var cat = url[0];
			
			var values = '';
			var input = $(this).find('a[href*="'+cat+'"].active');
			if(input.length != 0) {
				input.each(function(i){
					var url = $(this).attr('href');
					var url = url.split("?");
					var url = url[1].split("=");
					var val = url[1];
				
					values += val;
					if(i+1 != input.length) {
						values += ",";
					}
				});
				var state = {};
				state[cat] = values;
				$.bbq.pushState(state);
			} else {
				$.bbq.removeState(cat);
			}
		});
	});
	
	
	$('#filter a, a.quickfilter').live( 'click', function(e){
		e.preventDefault();
		var state = {};
		
		var url = $(this).attr('href');
		var url = url.split("?");
		var url = url[1].split("=");
		var cat = url[0];
		var val = url[1];

		state[ cat ] = val;
		$.bbq.pushState( state );
	});
	
	
	function filterTripexplorer(value) {
		if (value == 'all' || value == '') {
			value = 'all';
			$('#masonry').children('.hide').toggleClass('hide').animate({opacity: 1});
		} else {
			$("#masonry .box").removeClass("preselect").removeClass("hide");
			$("#masonry [data-sort*='"+value.toLowerCase()+"']").addClass("preselect").animate({opacity: 1});
			
			$("#masonry .box:not(.preselect)").animate({opacity: 0}).addClass("hide");
			$("#masonry .box").removeClass("preselect");
		}
		
		if($(".masonry-brick:not(.hide)").length == 0) {
			if(!$(".TripExplorer .default_message:visible").length == 1) {
				$(".TripExplorer .no_results").show();
			}
		} else {
			$(".TripExplorer .no_results").hide();
		}

		$("#filter a").removeClass("active");
		$("#filter ."+value).addClass("active");
		$('#masonry').masonry('reload');
	}
	
	
	$.param.fragment.ajaxCrawlable(true);
	
	var data = '';
	var old_data = '';
	
	$(window).bind('hashchange', function(e) {

		var params = $.bbq.getState();
		var filter = '';
		data = ''
		$.each(params, function(e, value){

			if(e == "filter") {
				filter = value;
			}
			
			if(e == "Activities" || e == "Seasons" || e == "For" || e == "North+Island" || e == "South+Island") {
				data += '&'+e+'='+value;
				var active = value.split(",");
				$("#trip_explorer a[href*='"+e+"=']").removeClass("active");
				for(var i = 0; i < active.length; i++) {
					$("#trip_explorer a[href*='"+e+"='][href*='"+active[i]+"']").addClass("active");
				}
			}
			if($(".BookPage").length != 0 && (e == "North+Island" || e == "South+Island")) {
				inSelections("destination", decodeURI(value.replace(/\+/g, " ")));
			}
			
		});
		

		if(data != old_data) {
			$.ajax({
				type: "GET",
				url: location.pathname,
				data: data,
				success: function(response){
					$("#masonry").html($(response).find("#masonry").children()).masonry('reload');
					init_widgets();
					filterTripexplorer(filter);
				}
			});
			old_data = data;
		} else {
			filterTripexplorer(filter);
		}

		if(data == '' && old_data == '') {
			$(".TripExplorer .default_message").show();
			$(".TripExplorer #filter").hide();
			$(".TripExplorer .no_results").hide();
		} else {
			$(".TripExplorer #filter").show();
			$(".TripExplorer .default_message").hide();
		}
		
		
		init_widgets();
		init_booking();

	});

	$(window).trigger('hashchange');

});
