/*
 ### jQuery Star Rating Plugin v3.13 - 2009-03-26 ###
 * Home: http://www.fyneworks.com/jquery/star-rating/
 * Code: http://code.google.com/p/jquery-star-rating-plugin/
 *
	* Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 ###
*/

/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
	
	// IE6 Background Image Fix
	if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
	// Thanks to http://www.visualjquery.com/rating/rating_redux.html
	
	// plugin initialization
	$.fn.rating = function(options){
		if(this.length==0) return this; // quick fail
		
		// Handle API methods
		if(typeof arguments[0]=='string'){
			// Perform API methods on individual elements
			if(this.length>1){
				var args = arguments;
				return this.each(function(){
					$.fn.rating.apply($(this), args);
    });
			};
			// Invoke API method handler
			$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.rating.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Allow multiple controls with the same name by making each call unique
		$.fn.rating.calls++;
		
		// loop through each matched element
		this
		 .not('.star-rating-applied')
			.addClass('star-rating-applied')
		.each(function(){
			
			// Load control parameters / find context / etc
			var control, input = $(this);
			var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
			var context = $(this.form || document.body);
			
			// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
			var raters = context.data('rating');
			if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls };
			var rater = raters[eid];
			
			// if rater is available, verify that the control still exists
			if(rater) control = rater.data('rating');
			
			if(rater && control)//{// save a byte!
				// add star to control if rater is available and the same control still exists
				control.count++;
				
			//}// save a byte!
			else{
				// create new control if first star or control element was removed/replaced
				
				// Initialize options for this raters
				control = $.extend(
					{}/* new object */,
					options || {} /* current call options */,
					($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
					{ count:0, stars: [], inputs: [] }
				);
				
				// increment number of rating controls
				control.serial = raters.count++;
				
				// create rating element
				rater = $('<span class="star-rating-control"/>');
				input.before(rater);
				
				// Mark element for initialization (once all stars are ready)
				rater.addClass('rating-to-be-drawn');
				
				// Accept readOnly setting from 'disabled' property
				if(input.attr('disabled')) control.readOnly = true;
				
				// Create 'cancel' button
				rater.append(
					control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
					.mouseover(function(){
						$(this).rating('drain');
						$(this).addClass('star-rating-hover');
						//$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).removeClass('star-rating-hover');
						//$(this).rating('blur');
					})
					.click(function(){
					 $(this).rating('select');
					})
					.data('rating', control)
				);
				
			}; // first element of group
			
			// insert rating star
			var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
			rater.append(star);
			
			// inherit attributes from input element
			if(this.id) star.attr('id', this.id);
			if(this.className) star.addClass(this.className);
			
			// Half-stars?
			if(control.half) control.split = 2;
			
			// Prepare division control
			if(typeof control.split=='number' && control.split>0){
				var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
				var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
				star
				// restrict star's width and hide overflow (already in CSS)
				.width(spw)
				// move the star left by using a negative margin
				// this is work-around to IE's stupid box model (position:relative doesn't work)
				.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
			};
			
			// readOnly?
			if(control.readOnly)//{ //save a byte!
				// Mark star as readOnly so user can customize display
				star.addClass('star-rating-readonly');
			//}  //save a byte!
			else//{ //save a byte!
			 // Enable hover css effects
				star.addClass('star-rating-live')
				 // Attach mouse events
					.mouseover(function(){
						$(this).rating('fill');
						$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).rating('blur');
					})
					.click(function(){
						$(this).rating('select');
					})
				;
			//}; //save a byte!
			
			// set current selection
			if(this.checked)	control.current = star;
			
			// hide input element
			input.hide();
			
			// backward compatibility, form element to plugin
			input.change(function(){
    $(this).rating('select');
   });
			
			// attach reference to star to input element and vice-versa
			star.data('rating.input', input.data('rating.star', star));
			
			// store control information in form (or body when form not available)
			control.stars[control.stars.length] = star[0];
			control.inputs[control.inputs.length] = input[0];
			control.rater = raters[eid] = rater;
			control.context = context;
			
			input.data('rating', control);
			rater.data('rating', control);
			star.data('rating', control);
			context.data('rating', raters);
  }); // each element
		
		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
		
		return this; // don't break the chain...
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.rating, {
		// Used to append a unique serial number to internal control ID
		// each time the plugin is invoked so same name controls can co-exist
		calls: 0,
		
		focus: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.focus) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // focus handler, as requested by focusdigital.co.uk
			if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.focus
		
		blur: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.blur) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // blur handler, as requested by focusdigital.co.uk
			if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.blur
		
		fill: function(){ // fill to the current mouse position.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars and highlight them up to this element
			this.rating('drain');
			this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.rating.fill
		
		drain: function() { // drain all the stars.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars
			control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
		},// $.fn.rating.drain
		
		draw: function(){ // set value and stars to reflect current selection
			var control = this.data('rating'); if(!control) return this;
			// Clear all stars
			this.rating('drain');
			// Set control value
			if(control.current){
				control.current.data('rating.input').attr('checked','checked');
				control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on');
			}
			else
			 $(control.inputs).removeAttr('checked');
			// Show/hide 'cancel' button
			control.cancel[control.readOnly || control.required?'hide':'show']();
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
		},// $.fn.rating.draw
		
		
		
		
		
		select: function(value,wantCallBack){ // select a value
					
					// ***** MODIFICATION *****
					// Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27
					//
					// ***** LIST OF MODIFICATION *****
					// ***** added Parameter wantCallBack : false if you don't want a callback. true or undefined if you want postback to be performed at the end of this method'
					// ***** recursive calls to this method were like : ... .rating('select') it's now like .rating('select',undefined,wantCallBack); (parameters are set.)
					// ***** line which is calling callback
					// ***** /LIST OF MODIFICATION *****
			
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// clear selection
			control.current = null;
			// programmatically (based on user input)
			if(typeof value!='undefined'){
			 // select by index (0 based)
				if(typeof value=='number')
 			 return $(control.stars[value]).rating('select',undefined,wantCallBack);
				// select by literal value (must be passed as a string
				if(typeof value=='string')
					//return
					$.each(control.stars, function(){
						if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack);
					});
			}
			else
				control.current = this[0].tagName=='INPUT' ?
				 this.data('rating.star') :
					(this.is('.rater-'+ control.serial) ? this : null);

			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
			// find data for event
			var input = $( control.current ? control.current.data('rating.input') : null );
			// click callback, as requested here: http://plugins.jquery.com/node/1655
					
					// **** MODIFICATION *****
					// Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27
					//
					//old line doing the callback :
					//if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
					//
					//new line doing the callback (if i want :)
					if((wantCallBack ||wantCallBack == undefined) && control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
					//to ensure retro-compatibility, wantCallBack must be considered as true by default
					// **** /MODIFICATION *****
					
  },// $.fn.rating.select
		
		
		
		
		
		readOnly: function(toggle, disable){ // make the control read-only (still submits value)
			var control = this.data('rating'); if(!control) return this;
			// setread-only status
			control.readOnly = toggle || toggle==undefined ? true : false;
			// enable/disable control value submission
			if(disable) $(control.inputs).attr("disabled", "disabled");
			else     			$(control.inputs).removeAttr("disabled");
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
		},// $.fn.rating.readOnly
		
		disable: function(){ // make read-only and never submit value
			this.rating('readOnly', true, true);
		},// $.fn.rating.disable
		
		enable: function(){ // make read/write and submit value
			this.rating('readOnly', false, false);
		}// $.fn.rating.select
		
 });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.rating.options.cancel = 'Clear';
	*/
	$.fn.rating.options = { //$.extend($.fn.rating, { options: {
			cancel: 'Cancel Rating',   // advisory title for the 'cancel' link
			cancelValue: '',           // value to submit when user click the 'cancel' link
			split: 0,                  // split the star into how many parts?
			
			// Width of star image in case the plugin can't work it out. This can happen if
			// the jQuery.dimensions plugin is not available OR the image is hidden at installation
			starWidth: 16//,
			
			//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
			//half:     false,         // just a shortcut to control.split = 2
			//required: false,         // disables the 'cancel' button so user can only select one of the specified values
			//readOnly: false,         // disable rating plugin interaction/ values cannot be changed
			//focus:    function(){},  // executed when stars are focused
			//blur:     function(){},  // executed when stars are focused
			//callback: function(){},  // executed when a star is clicked
 }; //} });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default implementation ###
		The plugin will attach itself to file inputs
		with the class 'multi' when the page loads
	*/

	
	
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/






/* #### EIGENE FUNKTIONEN ######################################################### */




$(function() { 
	$("#tabs").tabs({
		collapsible: true,
		selected: -1,
		fx: { height: 'toggle' }
	}); 
});


function duration(valueMin, valueMax) {

	var duration = '';
	
	if(valueMin == 1 && valueMax == 29) {
		duration = 'mindestens 1 Nacht';
	} else if(valueMin == 1 && valueMax == 1) {
		duration = valueMax + ' Nacht';
	} else if(valueMin == 29 && valueMax == 29) {
		duration = 'mindestens 28 N&auml;chte';
	} else if(valueMin > 1 && valueMax == 29) {
		duration = 'mindestens ' + valueMin + ' N&auml;chte';
	} else {
		duration = valueMin + ' bis ' + valueMax + ' N&auml;chte';
	}
	
	return duration;
}

function getCurrencySign() {
    if ($.cookie("currency") == "ch") {
        return "CHF";
    }
 
    return "&euro;";
}

function price(valueMin, valueMax) {

	var priceMin = minPriceFromSlider('unbegrenzt', valueMin, valueMax);
	var priceMax = maxPriceFromSlider('nicht eingeschr&auml;nkt', valueMin, valueMax);
	var price = '';
	
	if(priceMin == 'unbegrenzt' && priceMax == 'nicht eingeschr&auml;nkt') {
		price = 'nicht eingeschr&auml;nkt';
	} else if(priceMin == 0 && priceMax == 0) {
		price = 'bis '+ 25 + ' ' + getCurrencySign();
	} else if(priceMin == 'unbegrenzt' && priceMax > 0 && priceMax != 'nicht eingeschr&auml;nkt') {
		price = 'bis '+ Math.round(priceMax) + ' ' + getCurrencySign();
	}  else if(priceMin != 'nicht eingeschr&auml;nkt' && priceMin > 0 && priceMax == 'nicht eingeschr&auml;nkt') {
		price = 'ab '+ Math.round(priceMin) + ' ' + getCurrencySign();
	}  else if(priceMin == priceMax && priceMin != 'nicht eingeschr&auml;nkt') {
		price = 'ungefähr '+ Math.round(priceMin) + ' ' + getCurrencySign();
	}  else if(priceMin == 'nicht eingeschr&auml;nkt' && priceMin == 'nicht eingeschr&auml;nkt') {
		price = 'ab '+ 4000 + ' ' + getCurrencySign();
	} else {
		price = Math.round(priceMin) + ' ' + getCurrencySign() + ' bis ' + Math.round(priceMax) + ' ' + getCurrencySign();
	}
	
	return price;
}

function minPriceFromSlider(priceMin, valueMin, valueMax)
{
    // Minimum-Wert festlegen
	if(valueMin > 0 && valueMin <= 8) {
  		priceMin = valueMin * 25;
	} else if(valueMin > 8 && valueMin <= 18) {
		priceMin = (valueMin - 4) * 50;
	} else if(valueMin > 18 && valueMin <= 26) {
		priceMin = (valueMin - 11) * 100;
	} else if(valueMin > 26 && valueMin <= 36) {
		priceMin = (valueMin - 20) * 250;
	} 
	
	return priceMin;
}

function maxPriceFromSlider(priceMax, valueMin, valueMax)
{
    // Maximum-Wert festlegen
	if(valueMax > 0 && valueMax <= 8) {
  		priceMax = valueMax * 25;
	} else if(valueMax > 8 && valueMax <= 18) {
		priceMax = (valueMax - 4) * 50;
	} else if(valueMax > 18 && valueMax <= 26) {
		priceMax = (valueMax - 11) * 100;
	} else if(valueMax > 26 && valueMax <= 36) {
		priceMax = (valueMax - 20) * 250;
	}
	return priceMax;
}

function ConvertPriceToSliderPosition(price)
{
    
    price =  price * getExchangeRate();
    
    if (price <= 200)
    {
        price = price / 25;
    }
    else if (price >= 201 && price <= 700)
    {
        price = (price / 50) + 4;
    }
    else if (price >= 701 && price <= 1500)
    {
        price = (price / 100) + 11;
    }
    else if (price >= 1501)
    {
        price = (price / 250) + 20;
    }
    
    return price;
}

function stars (numberStars) {
	var string = '';
  
	if(numberStars == 0) {
  		string = '<span class="star-inactive"></span><span class="star-inactive"></span><span class="star-inactive"></span><span class="star-inactive"></span><span class="star-inactive"></span>';
	} else if(numberStars == 1) {
		string = '<span class="star-active"></span><span class="star-inactive"></span><span class="star-inactive"></span><span class="star-inactive"></span><span class="star-inactive"></span>';
	} else if(numberStars == 2) {
		string = '<span class="star-active"></span><span class="star-active"></span><span class="star-inactive"></span><span class="star-inactive"></span><span class="star-inactive"></span>';
	} else if(numberStars == 3) {
		string = '<span class="star-active"></span><span class="star-active"></span><span class="star-active"></span><span class="star-inactive"></span><span class="star-inactive"></span>';
	} else if(numberStars == 4) {
		string = '<span class="star-active"></span><span class="star-active"></span><span class="star-active"></span><span class="star-active"></span><span class="star-inactive"></span>';
	} else if(numberStars == 5) {
		string = '<span class="star-active"></span><span class="star-active"></span><span class="star-active"></span><span class="star-active"></span><span class="star-active"></span>';
	}
	return string;
}

$(document).ready(function() {
	
   InitWizard();
   
});

// Wizard mit den Werten aus der URL intialisieren
function InitWizard()
{
    // Hash laden
    var hash = decodeURIComponent(location.hash);
    hash = $.deparam.fragment(hash);
    
    
	// Freitextsuche
    $("#freetextTextBox").attr("value", hash['freetext']);
	
	
	// Reiseziele
	if(hash['pnlZiel']) {
		var destinations = hash['pnlZiel'].split(',');
		$.each(destinations, function(index, value) { 
			$('#content-reiseziel input[id*="_' + value + '_"]').attr('checked', true);
			$('#result-reiseziel li[rel*="_' + value + '_"]').show(); 
		});
		// Sonderfall Deutschland
    	if($('#content-reiseziel input#reiseziel_id_r269_').attr('checked')) {
    		$('#content-reiseziel input.wizard-checkbox-deutschland').attr('checked', true);
    	}
	}
	
	
	// Reisthemen
	if(hash['pnlAnwendungen']) {
		var topics = hash['pnlAnwendungen'].split(',');
		$.each(topics, function(index, value) { 
			$('#content-reisethema input[id*="_' + value + '_"]').attr('checked', true);
			$('#result-reisethema li[rel*="_' + value + '_"]').show(); 
		});
	}
	
	
	// Weiteres
	if(hash['pnlOther']) {
		var other = hash['pnlOther'].split(',');
		$.each(other, function(index, value) { 
			$('#content-ausstattung input[id*="_' + value + '_"]').attr('checked', true);
			$('#result-ausstattung li[rel*="_' + value + '_"]').show(); 
		});
	}
	  
	  
    // Dauer
	var sliderDurationValues = [1, 29];	
	if (hash['pnlDauer']) {
    	var durations = hash['pnlDauer'].split(',');
    	if (durations[0] != "" && durations[1] != "") {
			sliderDurationValues = [durations[0], durations[1]];
        }
    };
	$("#wizard-duration-slider").slider({
		range: true,
		min: 1,
		max: 29,
		step: 1,
		values: sliderDurationValues,
		slide: function(event, ui) {
			$("#wizard-duration-value").html(duration(ui.values[0], ui.values[1]));
		},
		change: function(event, ui) {
			durationSelected();
		}
	});
	$("#wizard-duration-value").html(
		duration($("#wizard-duration-slider").slider("values", 0), 
		$("#wizard-duration-slider").slider("values", 1))
	);
	
	
	// Hin- und Rückreise
	var fromDate = "";
	var toDate = "";
	if (hash['pnlDauer'])
	{
        var durations = hash['pnlDauer'].split(',');
    	if (durations[2] != "") {
			fromDate = durations[2].replace("/", ".").replace("/", ".");
        }
        if (durations[3] != "") {
			toDate = durations[3].replace("/", ".").replace("/", ".");
        }
    };
    $("#wizard-textbox-from").attr("value", fromDate);
    $("#wizard-textbox-until").attr("value", toDate);
    

    // Preis
    var sliderPriceValues = [0, 37];
    if (hash['preis']) {
    	var prices = hash['preis'].split(',');
    	if (prices[0] != "" && prices[1] != "") {
			sliderPriceValues = [ConvertPriceToSliderPosition(prices[0]), ConvertPriceToSliderPosition(prices[1])];

        }
    };	
	$("#wizard-price-slider").slider({
		range: true,
		min: 0,
		max: 37,
		step: 1,
		values: sliderPriceValues,
		slide: function(event, ui) {
			$("#wizard-price-value").html(price(ui.values[0], ui.values[1]));
		},
		change: function(event, ui){	
		    sliderPreisChange(ui, minPriceFromSlider(0, ui.values[0], ui.values[1]), maxPriceFromSlider(100000, ui.values[0], ui.values[1]), ui.values[0], ui.values[1]);
		}
	});
	$("#wizard-price-value").html(
		price($("#wizard-price-slider").slider("values", 0),
		$("#wizard-price-slider").slider("values", 1))
	);
	
	
	// Sterne
	var sliderStarsValues = [0, 37];
    if (hash['stars']) {
    	var starValues = hash['stars'].split(',');
        sliderStarsValues = [starValues[0], starValues[1]];
    };   
	$("#wizard-stars-slider").slider({
		range: true,
		min: 0,
		max: 5,
		step: 1,
		values: sliderStarsValues,
		slide: function(event, ui) {
			var min = stars(ui.values[0]);
			var max = stars(ui.values[1]);
			$("#wizard-stars-value").html(min + '<span>&nbsp;bis&nbsp;</span>' + max);
		},
		change: function(event, ui) {
			sliderStarsChange(ui, ui.values[0], ui.values[1]);
			
		}
	});	
	$("#wizard-stars-value").html(stars($("#wizard-stars-slider").slider("values", 0)) + '<span>&nbsp;bis&nbsp;</span>' + stars($("#wizard-stars-slider").slider("values", 1)));
    
  	
	FITMoveDateTo();
  	
	/*
    
    if (query != null)
    {

        FITMoveDateTo();
    }
    */
}

function durationSelected()
{
    // Hash laden
    var hash = decodeURIComponent(location.hash);
    hash = $.deparam.fragment(hash);
    
    // Gewähltes Datum
    var selectedFromDate = null;
    if($("#wizard-textbox-from").val()!='') { selectedFromDate = new Date($("#wizard-textbox-from").datepicker("getDate")); }
    var selectedToDate = null;
    if($("#wizard-textbox-until").val()!='') { selectedToDate = new Date($("#wizard-textbox-until").datepicker("getDate")); }
    
    // Gewählte Dauer
    var minDuration = $("#wizard-duration-slider").slider("values", 0);
    var maxDuration = $("#wizard-duration-slider").slider("values", 1);
    
    // Mindest-Rückreisedatum einstellen
    if(!selectedFromDate) {
    	$("#wizard-textbox-until").datepicker(
			"option",
			"minDate", 
			+minDuration
		);
    }
    else
    {
    	$("#wizard-textbox-until").datepicker(
			"option",
			"minDate", 
			new Date(selectedFromDate.getTime() + minDuration*24*60*60*1000)
		);  
    }
    
    // Gewähltes Datum im richtigen Format auslesen
    selectedFromDate = $("#wizard-textbox-from").val().replace(".", "/").replace(".", "/");
    selectedToDate = $("#wizard-textbox-until").val().replace(".", "/").replace(".", "/");
    
    // Suchergebnisse aktualisieren
    sliderDurationOrDatesChange(
		minDuration, 
		maxDuration, 
		selectedFromDate,
		selectedToDate
	);

}
/* OLD FUNCTION
function CorrectToDateByDuration(toDate, durationStart)
{
    var localFromDate = $("#wizard-datepicker-from input").datepicker("getDate");
    var localToDate = $("#wizard-datepicker-until input").datepicker("getDate");
    if (new Number(durationStart) < 2 || localToDate == null) return toDate;
    if (new Date(localFromDate.getTime() + new Number(durationStart)*24*60*60*1000) > localToDate)
    {
        toDate = ToDateString(new Date(localFromDate.getTime() + new Number(durationStart)*24*60*60*1000)); 
    }
    return toDate;
}

*/

$(document).ready(function() {

	$(".search-reiseziel-toggle").click(function() {
		$(".search-reiseziel").toggle('blind');
		return false;
	});
	
	
	$("#wizard-datepicker-from input").datepicker({ 
				dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
				monthNames: ['Januar','Februar','MÃ¤rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
				firstDay: 1,
				minDate: 1,
				dateFormat: 'dd.mm.yy',
				showOn: 'both',
				buttonImage: 'img/datepicker.gif',
				showAnim: 'fadeIn',
				onSelect: fromDateSelected
		});

	

		$("#wizard-datepicker-until input").datepicker({ 
				dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
				monthNames: ['Januar','Februar','MÃ¤rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
				firstDay: 1,
				minDate: 1,
				dateFormat: 'dd.mm.yy',
				showOn: 'both',
				buttonImage: 'img/datepicker.gif',
				showAnim: 'fadeIn',
				onSelect: toDateSelected
		});

	
	// Termine Auswahl Personen, Zimmer, Verpflegung

	$('.termin-select-person').click(function() {
		$('.termin-select-person').removeClass('selected');
		$(this).addClass('selected');
	});
	
	$('.termin-select-zimmer').click(function() {
		$('.termin-select-zimmer').removeClass('selected');
		$(this).addClass('selected');
	});
	
	$('.termin-select-verpflegung').click(function() {
		$('.termin-select-verpflegung').removeClass('selected');
		$(this).addClass('selected');
	});
	
	
	// Freitextsuche
	
	$(".wizard-freetext input").autocomplete({
            	
		minLength: 2,
		source: function(request, response) {
			$.ajax({
				url: "/guenstig/dataprovider.aspx",
				dataType: "json",
				data: {
					source: "autocomplete",
					count: 5,
					input: request.term
				},
				success: function(data) {
					response($.map(data.autocomplete, function(item) {
						return {
							label: item.text ,
							value: item.text
						}
					}))
				}
			})
		}
	}).bind('autocompleteclose', function(){ $(this).val(stripHTML($(this).val())); });
	
});

function stripHTML(oldString) { return oldString.replace(/(<([^>]+)>)/ig,""); };

function fromDateSelected(dateText, inst)
{
    // Hash laden
    var hash = decodeURIComponent(location.hash);
    hash = $.deparam.fragment(hash);
    
    // Gewähltes Datum
    var selectedFromDate = null;
    if($("#wizard-textbox-from").val()!='') { selectedFromDate = new Date($("#wizard-textbox-from").datepicker("getDate")); }
    var selectedToDate = null;
    if($("#wizard-textbox-until").val()!='') { selectedToDate = new Date($("#wizard-textbox-until").datepicker("getDate")); }
    
    // Default-Werte
    var minDuration = 0;
    var maxDuration = 29;
    var fromDate = '';
    var toDate = '';
    var minDifference = 22;
    
    // URL-Werte auslesen
    if(hash['pnlDauer']) {
	    var durationAndDates = hash['pnlDauer'].split(',');
	    if (durationAndDates[0] != "") {
			minDuration = durationAndDates[0];
		}
		if (durationAndDates[1] != "") {
			maxDuration = durationAndDates[1];
		}
		if (durationAndDates[2] != "") {
			fromDate = durationAndDates[2].replace("/", ".").replace("/", ".");
		}
		if (durationAndDates[3] != "") {
			fromDate = durationAndDates[3].replace("/", ".").replace("/", ".");
		}
	}
	
	// Neue Datums-Werte bestimmen
	if(!selectedToDate) 
	{
		
		if(minDuration == 0)
		{
			selectedToDate = new Date(selectedFromDate.getTime() + minDifference*24*60*60*1000);
		}
		else
		{
			if(minDuration > minDifference)
			{
				selectedToDate = new Date(selectedFromDate.getTime() + minDuration*24*60*60*1000);
			}
			else
			{
				selectedToDate = new Date(selectedFromDate.getTime() + minDifference*24*60*60*1000);
			}
		}
	}
	else
	{
		if(minDuration == 0)
		{
			if(selectedToDate <= selectedFromDate)
			{
				selectedToDate = new Date(selectedFromDate.getTime() + 1*24*60*60*1000);
			}
			else
			{
				selectedToDate = selectedToDate;
			}
		}
		else
		{
			if(selectedToDate <= new Date(selectedFromDate.getTime() + minDuration*24*60*60*1000))
			{
				selectedToDate = new Date(selectedFromDate.getTime() + minDuration*24*60*60*1000);
			}
			else
			{
				selectedToDate = selectedToDate;
			}
		}
	}
	
	// Minimal auswählbares Datum im ToDate-Picker einstellen
	if(minDuration == 0)
	{
		$("#wizard-textbox-until").datepicker(
			"option",
			"minDate", 
			new Date(selectedFromDate.getTime() + 1*24*60*60*1000)
		);
	}
	else 
	{
		$("#wizard-textbox-until").datepicker(
			"option" , 
			"minDate", 
			new Date(selectedFromDate.getTime() + minDuration*24*60*60*1000)
		);
	}
	
	// Datum im ToDate-Picker einstellen
	$("#wizard-textbox-until").datepicker("setDate", selectedToDate);
	
	// Gewähltes Datum im richtigen Format auslesen
    selectedFromDate = $("#wizard-textbox-from").val().replace(".", "/").replace(".", "/");
    selectedToDate = $("#wizard-textbox-until").val().replace(".", "/").replace(".", "/");
    
    // Suchergebnisse aktualisieren
    sliderDurationOrDatesChange(
		minDuration, 
		maxDuration, 
		selectedFromDate,
		selectedToDate
	);
}

/* OLD FUNCTION
function fromDateSelected(dateText, inst)
{
    fromDate = dateText;
    var durationAndDates = query.get("pnlDauer");
    if (durationAndDates == "")
    {
        durationAndDates = ",,,";
    }
    FITMoveDateTo();
    var toDate = $("#wizard-textbox-until").attr("value");
    if (toDate == "")
    {
        toDate = durationAndDates.split(',')[3];
    }
    sliderDurationOrDatesChange(durationAndDates.split(',')[0], durationAndDates.split(',')[1], 
        fromDate.replace(".", "/").replace(".", "/"), toDate.replace(".", "/").replace(".", "/"));
}


*/

function toDateSelected(dateText, inst)
{
	// Hash laden
    var hash = decodeURIComponent(location.hash);
    hash = $.deparam.fragment(hash);
    
    // Gewähltes Datum
    var selectedFromDate = null;
    if($("#wizard-textbox-from").val()!='') { selectedFromDate = new Date($("#wizard-textbox-from").datepicker("getDate")); }
    var selectedToDate = null;
    if($("#wizard-textbox-until").val()!='') { selectedToDate = new Date($("#wizard-textbox-until").datepicker("getDate")); }
    
    // Default-Werte
    var minDuration = 0;
    var maxDuration = 29;
    var fromDate = '';
    var toDate = '';
    var minDifference = 22;
    
    // URL-Werte auslesen
    if(hash['pnlDauer']) {
	    var durationAndDates = hash['pnlDauer'].split(',');
	    if (durationAndDates[0] != "") {
			minDuration = durationAndDates[0];
		}
		if (durationAndDates[1] != "") {
			maxDuration = durationAndDates[1];
		}
		if (durationAndDates[2] != "") {
			fromDate = durationAndDates[2].replace("/", ".").replace("/", ".");
		}
		if (durationAndDates[3] != "") {
			fromDate = durationAndDates[3].replace("/", ".").replace("/", ".");
		}
	}
	
	// Neue Datums-Werte bestimmen
	if(!selectedFromDate) 
	{
		if(minDuration == 0)
		{
			selectedFromDate = new Date(selectedToDate.getTime() - minDifference*24*60*60*1000);
		}
		else
		{
			if(minDuration > minDifference)
			{
				selectedFromDate = new Date(selectedToDate.getTime() - minDuration*24*60*60*1000);
			}
			else
			{
				selectedFromDate = new Date(selectedToDate.getTime() - minDifference*24*60*60*1000);
			}
		}
	}
	
	// Datum im FromDate-Picker einstellen
	$("#wizard-textbox-from").datepicker("setDate", selectedFromDate);
	
	// Gewähltes Datum im richtigen Format auslesen
    selectedFromDate = $("#wizard-textbox-from").val().replace(".", "/").replace(".", "/");
    selectedToDate = $("#wizard-textbox-until").val().replace(".", "/").replace(".", "/");
    
    // Suchergebnisse aktualisieren
    sliderDurationOrDatesChange(
		minDuration, 
		maxDuration, 
		selectedFromDate,
		selectedToDate
	);

}

/* OLD FUNCTION
function toDateSelected(dateText, inst)
{
    toDate = dateText;
    var durationAndDates = query.get("pnlDauer");
    if (durationAndDates == "")
    {
        durationAndDates = ",,,";
    }
    
    //sliderDurationOrDatesChange(durationAndDates.split(',')[0], durationAndDates.split(',')[1], durationAndDates.split(',')[2], toDate.replace(".", "/").replace(".", "/"));
}
*/


//dauer und dates
function FITMoveDateTo() {
    var minDateNumber = 2;
    if (FITGetMinDuration() >= 2)
    {
        minDateNumber = FITGetMinDuration() + 1;
    }
    var fromDate = new Date($("#wizard-datepicker-from input").datepicker("getDate"));

    if (fromDate != null)
    {

       minDateNumber += DaysBetween(new Date(),fromDate);
    }
    var toCurrentDateValue = $("#wizard-textbox-until").attr("value");
    $("#wizard-datepicker-until input").datepicker("option" , "minDate", minDateNumber);
    var toUpdatedDate = $("#wizard-datepicker-until input").datepicker("getDate");
    if (toCurrentDateValue != "" && toUpdatedDate == null)
    {
        $("#wizard-datepicker-until input").datepicker("setDate",  $("#wizard-datepicker-until input").datepicker("option", "minDate"));
    }
}

function FITGetMinDuration()
{
    // Hash laden
    var hash = decodeURIComponent(location.hash);
    hash = $.deparam.fragment(hash);
    
    var minDuration = 0;
    if (hash['pnlDauer']) {
    	var durations = hash['pnlDauer'].split(',');
    	if (durations[0] != "") {
			minDuration = durations[0];
        }
    };
    return minDuration;
}
/* OLD FUNCTION
function FITGetMinDuration()
{
    var minDuration = 0;
    if (query.get("pnlDauer") != "")
    {
        minDuration = new Number(query.get("pnlDauer").split(',')[0]);
    }
    return minDuration;
}
*/

function DaysBetween(date1, date2) {
	
	// The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);

}
//~dauer und dates

function GetDestinationCodes()
{
    var codes = "";
    var germany_selected = false;
    if($('#content-reiseziel input#reiseziel_id_r269_').attr('checked')) { 
    	germany_selected = true;
    }
    
    $("input", "#content-reiseziel").each(function(){
        if ($(this).attr("checked") && !($(this).hasClass('wizard-checkbox-deutschland') == true && germany_selected == true))
        {
            if (codes != "") codes += ",";
            codes += $(this).attr("value");
        }
    });
    return codes;
}

function GetAnwendungCodes()
{
    var codes = "";
    $("input", "#content-reisethema").each(function(){
        if ($(this).attr("checked"))
        {
            if (codes != "") codes += ",";
            codes += $(this).attr("value");
        }
    });
    return codes;
}

function GetAttributeCodes()
{
    var codes = "";
    $("input", "#content-ausstattung").each(function(){
        if ($(this).attr("checked"))
        {
            if (codes != "") codes += ",";
            codes += $(this).attr("value");
        }
    });
    return codes;
}

var durationStart = "", durationEnd = "", fromDate = "", toDate = "";

function InitWizardData()
{
    durationStart = ""; 
    durationEnd = ""; 
    fromDate = ""; 
    toDate = "";
}

$(function(){
	

	
	
	
	$('.uncheck-checkbox').live("click", function() {
		var id = $(this).parent().attr('rel');
		$('#' + id).attr('checked', false);
		$(this).parent().hide('blind');
		
		if (id.indexOf("reiseziel") >= 0)
		{
		    destinationSelected(GetDestinationCodes());
		}
		if (id.indexOf("reisethema") >= 0)
		{
		    anwendungSelected(GetAnwendungCodes());
		}
		if (id.indexOf("ausstattung") >= 0)
		{
		    attributeSelected(GetAttributeCodes());
		}
	});
	

	
	
	// Datepicker

	
	$("#wizard-date-min").datepicker();
	$("#wizard-date-max").datepicker();
	
	
	$('.meta a').click(function() {
		$(this).hide();
		$(this).parent().prev('.accordion').children('.hidden').show();
	});
	
	

	
});


/* START: Accordion ------------------  */

function initAccordion() {

	$(".accordion > div").hide();
			
	$(".accordion-link").click(function(){
	
		$(this).parent().children().each(function() {
    			$(this).css({height: $(this).height()});		
  		});
	
		if($(this).next().is(':hidden')) {			
			$(this).parent().children("div:visible").hide(0, function() {
    				
  			});			
			$(this).next().show(0, function() {
    				
  			});		
		} else {
			$(this).parent().children("div:visible").hide(0, function() {
    				
  			});

		}
		
		$(this).parent().children().each(function() {
    			$(this).css({height: 'auto'});
  		});
		
		return false;
	});
	
};

$(document).ready(function() {
	initAccordion();
});

/* END: Accordion ------------------  */


/* Zusatzleistungen  */

$(document).ready(function() {
    
    $('li.extra img').live("click", function() {
        
        // POST-Parameter Wert
        val = $(this).parent()
                      .next('input')
                      .val();
                      
        RemoveExtra(val);              
                      
        // Select Element - steht im Markup etwas eingeschachtelt davor
        context = $(this).parents('ul.treatments-list:first')
                          .prev('label')
                          .find('select');
                          
        
        // <option> mit Wert val aktivieren, attribute entfernen
        $("option[value='"+val+"']", context)
            .removeAttr('disabled')
            .removeClass('disabled');
        
        // <li> aus DOM entfernen    
        $(this).parents('li.extra:first').remove();
    });

    $('select.treatment').change(function(e) {
        
//        e.preventDefault();

        $('option:selected', this).each(function () {
            val = $(this).val();
            
            AddExtra(val);
            
            if (val != "") {
                $(this).addClass('disabled').attr('disabled', true);  
                $('<li class="extra">'+$(this).text()
                    +'<span><img alt="" src="img/kreuz.gif"></span>'
                    +'<input type="checkbox" value="'+val+'" name="extra-1-'+val+'" checked="checked" />'
                 +'</li>')
                .appendTo($(this)
                .parent()
                .parent()
                .next('ul'));
            }
        });
    })
});


function AddExtra(id)
{
    $("#tbHiddenExtras").val($("#tbHiddenExtras").val() + ";" + id);
    $("#tbHiddenExtras").change();
}

function RemoveExtra(id)
{
    $("#tbHiddenExtras").val($("#tbHiddenExtras").val().replace(";" + id, ""));
    $("#tbHiddenExtras").change();
}


/* Zahlweise (Radio)  */

$(document).ready(function() {
    
    $('div#payment-method input:radio').click(function() {
        index = $('div#payment-method input:radio').index(this);
        $('div#payment-info div').hide();
        $('div#payment-info div').eq(index).show();
    });
});





/* Tabellenzellen Hover Effekt */

$(document).ready(function() {    
    UpdateHoverable(); 
});

function UpdateHoverable()
{
    $('table.hoverable tr:gt(0)')
        .find('td')
        .hover(
            function () {
                     $(this).css({'background-color': '#BAED78'});
            }, 
            function () {
                     $(this).css({'background-color': '#E6E6E6'})
            }
        );	
}





$(document).ready(function() {

	/* Init jCalendar ----------------------------------- */    
	
	$('#datepickerFrom').datePicker({
                inline:true,
                'minDate': '+10d'
	});
	
	$('#datepickerTo').datePicker({
                inline:true,
                selectMultiple:true // allow multiple dates to be selected
	});
	
	//$('#frame-list li img').attr('class', 'fancybox').attr('rel', 'gallery').attr('href', 'http://www.fitreisen.de/guenstig/HotelPics/135/294x168/135002.jpg');
	
	$('#frame-list li img').each(function(index) {
		var src = $(this).attr('src');
		src = src.replace('294x168', '800x600');
		$('#panel').before('<a href="' + src + '" rel="gallery" style="display:none;"></a>');
	});
	
	if($('#container').hasClass('whitelabel')) {
		
		
		
		
		$("a[rel=gallery]").each(function() {
    		var link = $(this);
    		
    		$(link).colorbox({
    			transition: 'none',
				onComplete:function(){ 
					var offset_top = link.offset().top - $('#colorbox').height() / 2;
					if (offset_top < 0) { 
						offset_top = 0;
					}
					$('#colorbox').css('top', offset_top);
				}
			});
    		
    		/*

			$(link).fancybox({
				'onComplete': function() {
					var offset_top = link.offset().top - $('#colorbox').height() / 2;
						if (offset_top < 0) { offset_top = 0; }
						$('#colorbox').css('top', offset_top);
				}
			})
			*/
			
		})
	} else {
		
		
		$('a[rel=gallery]').fancybox({
			'transitionIn'	: 'none',
			'transitionOut' : 'none',
			'margin' : 0, 
	    	'padding' : 0
		})
		
		
	}

});


/* Hotel Detail Bild-Popup ----------------------------------- */
	
$('#panel img').live('click', function() {

	var src = $('#panel img:last').attr('src');
	src = src.replace('294x168', '800x600');
	
	$("a[rel=gallery][href='" + src + "']").trigger('click');

	
	
	

	return false;


});
	
	



/* Toggle "Abweichende Rechnungsadresse" */

$(document).ready(function() {
    $("span.invoice-address").click(function() {
        $('div#other-invoice-address').toggle()
        return false;
    });
});





/* AGB checken  */

$(document).ready(function() {
    $("form.ibe").submit(function() {
        if (true !== $('#agb').is(':checked')) {
            alert('Bitte akzeptieren Sie unsere AGB');
            return false;
        }
    });
});





/* Galerie auf der Hotel-Detail-Seite ----------------  */

$(document).ready(function() {

	$('#panel').wrap('<div class="bildunterschrift_container" />');
	
	$('#panel').prepend('<img src="/fileadmin/fitreisen.de_templates/img/icon-lupe.png" style="position: absolute; bottom: 20px; right: 14px;">');

	$('.frames img').live('click', function() {
    
        	largeImageDir = $(this).attr('src').replace('gallery/','gallery/large/');
        
        	$('#panel img:last').attr('src', largeImageDir);
        	
        	$('.bildunterschrift').remove();
        	
        	var description = '';
        	description = $(this).attr('alt');
        	if(description!='') {
        		$('#panel').after('<div class="bildunterschrift"><p>' + description + '</p></div>');
        	}
        	
        	
        	
        	$('a#lightbox-seed').attr('href', largeImageDir);
        
        	return false;
    	
    	});
    
    	$(".frames").css('height', 'auto');
    	$(".frames").jCarouselLite({
		btnNext: ".carousel a.next",
          	btnPrev: ".carousel a.prev",
          	visible: 4,
          	circular: false
		});
    
	$('ul#frame-list li:first img').click();
	
	
});

/* ENDE: Galerie auf der Hotel-Detail-Seite ----------------  */





$(document).ready(function() {
    
    /* Tooltip  */
	$('.tooltip').tipTip({
		activation: "click", 
		fadeIn: 0,
		delay: 0,
		keepAlive: 1,
		defaultPosition: 'top'
	}); 
	
	/* Currency Switcher  */
	$('#flaggen a').each(function() {
		var language = $(this).attr('data-language');
		var href = $(location).attr('href');
		$(this).attr('href', href);
		$(this).querystring('currency=' + language);
	});

});





/* Formularvalidierung */

$(document).ready(function() {
    
//    $.validator.addMethod("phoneDE", function(value, element) { 
//        return this.optional(element) || /^(((((00|\+)49[ \-/]{0,1})|0)[1-9][0-9]{1,4}[ \-/]{0,1}|(((00|\+)49\()|\(0)[1-9][0-9]{1,4}\))[0-9]{1,7}[ \-/]{0,1}[0-9]{1,5})$/.test(value); 
//    }, null);
//    
//    $.validator.addMethod("streetNumber", function(value, element) { 
//       return this.optional(element) || /^([A-ZÃ„Ã–Ãœ][a-zÃ¤Ã¶Ã¼ÃŸ]+(([.] )|( )|([-])))+[1-9][0-9]{0,3}[a-z]?$/.test(value); 
//    }, null);
//    
//    $.validator.addMethod("areacodeDE", function(value, element) { 
//       return this.optional(element) || /^[0-9]{5}$/.test(value); 
//    }, null);
//    
//    $.validator.addMethod("bankcodeDE", function(value, element) { 
//       return this.optional(element) || /[1-8][0-9]{2}[0-9]{5}/.test(value); 
//    }, null);

    $("form.ibe").validate({ 
        debug: true,
        errorPlacement: function(){ return; },
         rules: {
            "person-one['first-name']": {
                required: true
            },
            "person-one['last-name']": {
                required: true
            },
            "person-two['first-name']": {
                required: true
            },
            "person-two['last-name']": {
                required: true
            },
            "booking-person['email']": {
                required: true,
                email: true
            },
            "booking-person['phone']": {
                required: true
            },
            "booking-person['street']": {
                required: true
            },
            "booking-person['areacode']": {
                required: true
            },
            "booking-person['town']": {
                required: true
            },
            "terms['agreement']": 'required',
            "payment['account-holder']": {
                required: true
            },
            "payment['account-number']": {
                required: true
            },
            "payment['bank-code']": {
                required: true
            },
            "payment['bank-name']": {
                required: true
            }

        }
    });
});

 jQuery.fn.extend({  
   
    /** 
    * Position the first element in the jQuery list near another element  
    * using absolute positioning. The element should already have the  
    * proper z-Index set. 
    *  
    * @param string align 'bottom' for bottom left, or 'right' for top right, 
    *    'left' for top left, 'top' for above left. 
    */  
    makePositioned: function(align, element) {  
     var first = this.eq(0);  
     var pos, height, width, left, top, thisHeight, thisWidth;  
     pos = element.offset();  
     height = element.outerHeight(), width = element.outerWidth();  
     left = pos.left, top = pos.top;  
     thisHeight = first.outerHeight(), thisWidth = first.outerWidth();  
       
     switch (align) {   
       case 'bottom':  
         top += height;  
       break;  
       case 'right':  
         left += width;  
       break;  
       case 'left':  
         left = left - thisWidth;  
       break;  
       case 'top':  
         top = top - thisHeight;  
       break;  
     }  
    
     first.css({   
       top: parseInt(top)+'px',   
       left: parseInt(left)+'px',  
       position: 'absolute'  
     });  
       
     return this;  
    }  
   
 });
 
 
 
 $(document).ready(function() {
        // Deutschland
        $('.wizard-checkbox-deutschland-headline').live('click', function() {
            if ($('.wizard-checkbox-deutschland-headline').attr('checked')) {
                $('.wizard-checkbox-deutschland')
	               .attr('checked', true);
            }
            if (!($('.wizard-checkbox-deutschland-headline').attr('checked'))) {
                $('.wizard-checkbox-deutschland')
	               .attr('checked', false);
            }
        });
        $('.wizard-checkbox-deutschland').live('click', function() {
            if (!($(this).attr('checked'))) {
                $('.wizard-checkbox-deutschland-headline')
		               .attr('checked', false);
            };
            if (($(this).attr('checked'))) {
                var alleausgewaehlt = 1;
                $('.wizard-checkbox-deutschland').each(function() {
                    if (!($(this).attr('checked'))) {
                        alleausgewaehlt = 0;

                    }
                });
                if (alleausgewaehlt == 1) {
                    $('.wizard-checkbox-deutschland-headline').attr('checked', true);
                };
            }
        });
        

    });
