/*Browser Detection*/
var BrowserDetect = {
	init: function () {
    if(($.browser.msie) && (BrowserDetect.version == '6'))
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// Define a simple show(), hide() effect for the gallery for IE
// IE has problems fading in transparent PNG images, and the default
// effect is a fade effect. 
$.tools.overlay.addEffect("ieeffect", function(pos, done) {
		var conf = this.getConf(),
			w = $(window);
		if (!conf.fixed) {
			pos.top += w.scrollTop();
			pos.left += w.scrollLeft();
		}
		pos.position = conf.fixed ? 'fixed' : 'absolute';
		this.getOverlay().css(pos).show();
		done.call();
	},
	function(done) {
		this.getOverlay().hide();
		done.call();
	}
);

// this function is common for every app
function setOverlay(selectorOverlay)
{
	// check if the overlay element exists
	var overlayElement = $(selectorOverlay).attr('rel') || '';
	// If there is a rel attribute the element has to exist. If there is no rel attribute we cannot check it. 
	// The selectorOverlay has always to exist
	if (((overlayElement.length && $(overlayElement).length) || !overlayElement.length) && selectorOverlay.length > 0) {
		$(selectorOverlay).overlay({
			oneInstance: false,
			fixed: false,
			effect: ($.browser.msie?'ieeffect':'default'),
			closeOnClick: true,
			mask: {
				color: '#0057a7',
				loadSpeed: 200,
				opacity: 0.2
			}
		});
	}   
}

function deleteLastLine()
{
    var cntlinedBox = $('#shoppingCart .linedBox').length;
    if(cntlinedBox > 0)
    {   
        $('#shoppingCart .linedBox').each(function(countBox){
            if(countBox+1 == cntlinedBox)
            {
                $(this).removeClass('linedBox');
            }
        });
    }
}
function radioCheckW()
{
    $('.addAssuranceForm .insuranceTop input').each(function(){
        if($(this).attr('checked') != true)
        {
            $(this).parents('.insuranceList').find('.insuranceBot input, .insuranceBot label').css('display','none');
        }
    });
    if($.browser.msie) 
    {
        $('.addAssuranceForm .insuranceTop input').click(function() {
          this.blur();
          this.focus();
        });
    }
    $('.addAssuranceForm .insuranceTop input').change(function(){
        var list = $(this).parents('li.insuranceList');
        var currentRadio = list.find('input:radio').attr('checked', true);
        $('.addAssuranceForm .insuranceTop input:radio').each(function()
        {
            if($(this).attr('id') != currentRadio.attr('id'))
            {
                $(this).parents('.insuranceList').find('.insuranceBot input, .insuranceBot label').animate({
                    height: 'hide'
                }, 'fast');
            }
            else
            {
                $(this).parents('.insuranceList').find('.insuranceBot input, .insuranceBot label').animate({
                    height: 'show'
                }, 'fast');
            }
        });
        
    });
}

function updateShoppingCart(hide, priceSelect)
{
	var flobu;
	$(function(){
		flobu = createFlobu({
			base_obj: $('.shoppingCartHld')
		});
	}) ;
	flobu.enable();

	var shoppingCart = $('#shoppingCart').parents('.AjaxLoaded');
    var shoppingCartId = shoppingCart.attr('id');
	//alert(shoppingCartId);
    if(shoppingCart.css('display') == 'block')
    {
    	shoppingCart.fadeOut(200);
    }
    

    // this function is exectued after the shopping cart was updated
    // (see below)    
    $.priceUpdate = function() {
	    if(priceSelect != undefined) {
		    priceSelect.text($('#shoppingCart .carAllPrice .carPrice').text());
		    priceSelect.parent('td').find('.total').css('display', 'block');
	    }
	    var cntlinedBox = $('#shoppingCart .linedBox').length;
	    if(cntlinedBox > 0)
	    {
		    $('#shoppingCart .linedBox').each(function(countBox){
			    if(countBox+1 == cntlinedBox) {
				    $(this).removeClass('linedBox');
			    }
		    });
	    }
    }

    // on complete function is set
    document.Beans[shoppingCartId].setOnComplete($.priceUpdate);
    document.Beans[shoppingCartId].update();
    if(!hide)
    {
    	shoppingCart.fadeIn(800);
    }
    
    
	flobu.disable();
    
}

function hideShowBlogComm()
{
	$('.ArticleCommentViewer a.showComments').click(function(){
		$('.ArticleCommentViewer .hiddenCommentBox').animate({
			height: 'show'
		});
		$('.ArticleCommentViewer a.showComments').css('display','none');
		$('.ArticleCommentViewer a.hideComments').css('display','block');
	});
	$('.ArticleCommentViewer a.hideComments').click(function(){
		$('.ArticleCommentViewer .hiddenCommentBox').animate({
			height: 'hide'
		});
		$('.ArticleCommentViewer a.showComments').css('display','block');
		$('.ArticleCommentViewer a.hideComments').css('display','none');
	});
}

// ########################## XPLOSION IFrame integration #######################################
var Xplosion = {
	profiler: function(xpl_params) {
		// create xplosion profiling url
		var xpl_scriptUrl = document.location.protocol + '//ssl.xplosion.de/profiler.html?customer=berge-meer.de';
		for (xpl_param in xpl_params) {
			xpl_scriptUrl += '&' + xpl_param + '=' + encodeURIComponent(xpl_params[xpl_param]);
		}
		// write xplosion profiling iframe
		var xpl_profiler = document.createElement('iframe');
		xpl_profiler.src = xpl_scriptUrl;
		xpl_profiler.allowtransparency = 'true';
		xpl_profiler.framespacing = '0';
		xpl_profiler.frameBorder = 'no';
		xpl_profiler.scrolling = 'no';
		xpl_profiler.width = '1';
		xpl_profiler.height = '1';
		document.getElementsByTagName('BODY')[0].appendChild(xpl_profiler);
	}
};


// ########################## STEP 1 BOOKING FUNCTIONS #########################################3

var Step1 = {

	// Resets the result list
	reset: function () {
		$('#listOffset').val(0);
		$('#lastEntryDate').val(0);
	},

	// Initializes step1 and registers events
	init: function () {
		Step1.reset();
		// Scroll to top of page if page is reloaded to prevent loading a bunch of additional results
		$(window).scrollTop(0);

		// Step 1: select all filter checkboxes on load
		$('#propertyfilter input:checkbox').each(function(){
			$(this).attr('checked', true);
		});


		// ############# REGISTER EVENTS ######################
		
		// Step1::"Buchen" Button -> get Availability
		$('#departureDate .datetable a.booking').live('click', function() {
			var clickedButton = $(this);
			var flobu;
			$(function(){
				flobu = createFlobu({
					base_obj: $('.datetable')
				});
			}) ;

			flobu.enable();
			var link = $(this);
			$(this).parent('td').find('.button').addClass('clicked');
			$.getJSON($(this).attr('rel'), function(json){
				if(!json.error)
				{
					self.location.href = json.redirect;
					flobu.disable();
				}
				else
				{
					flobu.disable();
					var errorContent = '';
					switch(json.errorCode)
					{
						case 1:
							errorContent = 'Für Ihren Belegungswunsch nicht verfügbar';
							break;
						case 3:
							errorContent = 'Leider ausgebucht';
							break;
						default:	// all other (unknown) errors
							errorContent = 'Zur Zeit nicht buchbar';
							break;
					}
					clickedButton.parents('td').addClass('availabilityError').text(errorContent);
				}
			});
			return false;
		}); // END OF "Buchen" Button

		// Step1::Change of number of children shows ages box, change on select loads results
		$('#selectPersonsFilter select').change(function() {
			if ($(this).attr('id') == 'children') {
				var childrenVal = $(this).val();
				if (childrenVal=='0') {	// no children
					$('.childBox').slideUp('fast');
					// reset children ages
					$('.childBox select[name^=child]').each(function() {
						$(this).find('option:first').attr('selected', true);
					});	
				} else {
					// determine how many ages boxes to show by children value
					$('.childBox select[name^=child]').each(function() {
						if (childrenVal > $(this).index()) {
							$(this).show();
						} else {
							$(this).hide();
						}
					});	
					// change description text depending on number of children
					/*if (childrenVal == 1) {
						$('.childBox p').text('Bitte geben Sie das Alter des Kindes bei Reiseantritt an.');
					} else {
						$('.childBox p').text('Bitte geben Sie das Alter der Kinder bei Reiseantritt an.');
					}*/
					$('.childBox').show();
				}	
			}

			Step1.loadResults(true);
		}); // END OF show children age select box
	    
	   
		// step 1 filter: function to set/unset all filter checkboxes 
		$('#propertyfilter form input:checkbox').click(function(){ 
			// show "apply filters" button
			$('#propertyfilter .button').css('visibility', 'visible');

			var form = $(this).parents('form');
			var all = form.find('.first input[type=checkbox]');

			// if clicked on select all
			if ($(this).get(0) == all.get(0)) {
				// select or deselect all checkboxes depending on the 'all' checkbox state
				form.find('.listInput input[type=checkbox]').attr('checked', all.attr('checked'));
			} else {
				// any other checkbox
				// count checked checkboxes to determine the state of the 'all' checkbox
				var inputsAll = form.find('.listInput input[type=checkbox]').length;
				var inputsChecked = form.find('.listInput input[type=checkbox]:checked').length;
				if (inputsAll == inputsChecked) all.attr('checked', true);
				else all.attr('checked', false);
			}
		});

		// Step1::Apply filter options and search for dates
		$('#propertyfilter a.filter').click(function(){
			// load the results
			Step1.loadResults(true);
			return false;
		}); // END OF filter button action
		

		// ########### END OF REGISTER EVENTS

		// show children ages box if children are selected
		if ($('#selectPersonsFilter #children').val() > 0) {
			$('#selectPersonsFilter #children').trigger('change');
		} else {
			// Results are also loaded on change trigger, so do this in else only
			// Load results on init
			Step1.loadResults(true);
		}
	},
	
	// Check if there was an age given for each child
	issetChildrenAges: function() {
		var agesSet = true;
		// if number of children is > 0
		if ($('#selectPersonsFilter #children').val() > 0) {
			// children have been selected, check if age is set
			$('.childBox select[name^=child]:visible').each(function() {
				if ($(this).val() < 2 || $(this).val() > 17) {
					agesSet = false;
				}
			});
		}
		return agesSet;
	},

	// Loads date results. 
	// @param boolean clear Clear previous results or append new results
	loadResults: function (clear) {
		// unbind loading by scrolling while loading results 
		// see _departureDateTable for details of this function
		$(window).unbind('scroll');
		
		// hide "apply filters" button until checkboxes were changed
		$('#propertyfilter .button').css('visibility', 'hidden');

		// the clear parameter defines, if we clear all results so far
		// (i.e. when changing filters and loading a new result set)
		if (clear == null) clear = true;

		// Check if all children ages were set before loading results
		if (!Step1.issetChildrenAges()) { 
			$('#status-information tbody .no-result').text('Bitte geben Sie das Alter aller Kinder an.');
			$('#departureDate .datetable tbody').empty().append($('#status-information tbody').html());
			return;
		}

		// Check if there is an adult select field (there is no on children only trips)
		if ($('#selectPersonsFilter #adult').length > 0) {
			// check if at least one adult is set
			if ($('#selectPersonsFilter #adult').val() < 1) {
				$('#status-information tbody .no-result').text('Bitte geben Sie die Anzahl der mitreisenden Personen an (mindestens 1 Erwachsener).');
				$('#departureDate .datetable tbody').empty().append($('#status-information tbody').html());
				return;
			}
		} else {
			// check if at least on child is set
			if ($('#selectPersonsFilter #children').val() < 1) {
				$('#status-information tbody .no-result').text('Bitte geben Sie die Anzahl der mitreisenden Personen an (mindestens 1 Kind).');
				$('#departureDate .datetable tbody').empty().append($('#status-information tbody').html());
				return;
			}
		}
			

		var flobu;
		var base;
		base = $('div.datetable');
		// show flobu on top, if clear is true
		if (clear) {
			// reset values
			Step1.reset();
			flobu = createFlobu({
				base_obj: base
			});
		} else { 		// show on bottom if we are loading new results
			flobu = createFlobu({
				base_obj: base,
				bubble: { position: 'absolute', bottom: 0, top: 'auto' }
			});
		}

		flobu.enable();
		// select all relevant forms in the filter
		var allForms = $('#propertyfilter form, #selectPersonsFilter');
		var query = $('#propertyfilter form').eq(0).attr('action')+'?';

		var sep = '';
		// build the GET query string
		allForms.each(function(){
			query += sep + $(this).serialize();
			sep = '&';
		});
		$.getJSON(query, function(json){
			if(json.error) {
				clear = true;		// clear previous results on error
			}

			if (clear) {
				$('#departureDate .datetable tbody').empty();

			} else {
				// If more results were loaded by scrolling,
				// delete the last table row
				$('#morerow').remove();
			}
			$('#departureDate .datetable tbody').append(json.html);
			flobu.disable();
			// update the listOffset for new list items
			if (json.listOffset) {
				$('#listOffset').val(json.listOffset);
			}

			if (json.lastEntryDate) {
				$('#lastEntryDate').val(json.lastEntryDate);
			}
		});
		return false;
	}
};

// #################### END OF STEP 1 BOOKING FUNCTIONS ####################################


// #################### STEP 2 BOOKING FUNCTIONS ##########################################

var Step2 = {

	// Initializes step2 and registers events
	// init is called in step2 bean template
	init: function () {
		// ########## REGISTER EVENTS
		
		// Get rooms if hotel service changes
		// Not always is there a hotelServiceForm
		if ($('#hotelServiceForm select').length > 0) {
			$('#hotelServiceForm select').change(function(){
				Step2.getRooms();
			});
		}

		// Changing Rooms 
		$('.checkRoomsForm select').live('change', function() {
			var form = $(this).parents('form');
			var query = form.attr('action') + '?' + form.serialize();
			var select = $(this);
			$.getJSON(query, function(json){
				if(!json.error) {
					select.parents('table').find('label[for=' + select.attr('id') + '] .room_description').text(select.parents('table').find('#description_' + select.val()).val());
					updateShoppingCart(false, select.parents('form').find('.priceTotal'));
				} else {
					switch(json.errorCode) {
						case 3:
							alert('Die Teilnehmeranzahl passt nicht zu den ausgewählten Zimmern.');
							break;
						case 2:
						case 1:
						default:
							//alert(json.errorMsg);
					}
				}
			});
		});

		// Changing Zimmerbelegung
		$('.checkRoomsForm .roomTotal').live('change', function() {
			var form = $(this).parents('form');
			var query = form.attr('action') + '?' + form.serialize();

			// uncheck inactive choices, hide inactive information
			$('#roomResult input:radio').not(this)
				.attr('checked', false)
				.parents('form.checkRoomsForm')
					.removeClass('active')
					.find('table')
						.hide();
			// and show active choice and its information
			$(this).parents('form.checkRoomsForm')
					.addClass('active')
					.find('table')
						.show();
			$.getJSON(query, function(json){
				if(!json.error) {
					$('.error_list').html(json.errorMsg).hide();
					$('.buttonHolder.buttonHStd').show();
					updateShoppingCart(false, form.find('.priceTotal'));
				} else {
					updateShoppingCart(false);
				
					switch(json.errorCode) {
						case 4:
							//alert('Die Teilnehmeranzahl passt nicht zu den ausgewählten Zimmern.');
						break;
						case 3:
						//alert('Die Teilnehmeranzahl passt nicht zu den ausgewählten Zimmern.');
						break;
						case 2:
						case 1:
						default:
						//alert(json.errorMsg);
							$('.error_list').html(json.errorMsg).css('padding-bottom', '12px').css('padding-top', '2px').show();
							$('.buttonHolder.buttonHStd').hide();
					}
				}
			});
		}); 
		// ############### END OF REGISTER EVENTS

	},

	getRooms: function() {
		var flobu;
		$(function(){
			flobu = createFlobu({
					base_obj: $('div.contentContainerFull')
			});
		}) ;
		
		flobu.enable();
		var form = $('#hotelServiceForm');
		var query = form.attr('action') + '?' + form.serialize();
		$.getJSON(query, function(json){
			if (!json.error) {
				$('#roomResult').hide(500);
				$('#roomResult').html(json.data);

				// if no entry is checked, check the first one	
				if ($('#roomResult input[type="radio"]:checked').length == 0) {
					$('#roomResult input:radio').eq(0).attr('checked', true);
				}
				// Trigger checkRooms event
				$('#roomResult input[type="radio"]:checked').trigger('change');

				$('#roomResult').show(500);
				flobu.disable();
			} else {
				$('#roomResult input[type="radio"]:checked').trigger('change');
				switch(json.errorCode)
				{
					case 4:
						updateShoppingCart();
						//$('#roomResult').html('<span>' + json.errorMsg + '</span>');
						break;
					case 1:
					default:
						updateShoppingCart(true);
						$('#roomResult').html('<span>' + json.errorMsg + '</span>');
				}
				flobu.disable();
			}
		});
	}
};

// ###################### END OF STEP 2 BOOKING FUNCTIONS ############################################


// #################### STEP 4 BOOKING FUNCTIONS ##########################################

var Step4 = {

	// Initializes step4 and registers events
	// init is called in step4 bean template
	init: function() {

		// ########## REGISTER EVENTS FOR STEP 4 ###################

		// If country is changed, payment options need to be changed
		$('.tableFirst #countryData select').change(function(){
			Step4.loadPaymentOptions(0);	// use predefined payment type on country change
		});

		$('#payment input:radio').live('change', function(){
			Step4.loadPaymentOptions($(this).val());
		});

		// ############ END OF REGISTER EVENTS ####################

		// initialize payment panel when site loads, payment panel options depend on country selection
		
		//$('#payment input:radio:checked').trigger('change');
	},

	// int type Parameter to define the payment type, 0 = use predefined
	loadPaymentOptions: function(type) {
		var paymentPanel = $('#payment');
		var link = paymentPanel.attr('rel');
		var country = $('#contact_country').val();
		paymentPanel.stop();	// stop any animation
		paymentPanel.fadeOut(400);
		paymentPanel.load(link + '?type=' + type + '&country=' + country);
		paymentPanel.fadeIn(400);
	}

};

		
// ###################### END OF STEP 4 BOOKING FUNCTIONS ############################################

$(document).ready( function()
{
	
    $('#searchfield').focus( function() {
        valueInp = $(this).attr('value');
        $(this).attr('value','');
        $(this).blur( function() {
            if ($(this).attr('value') == '') {
                $(this).attr('value',valueInp);
            }
        });
    });

	//implement console.log for browsers that not support this e.g. IE disable ajax caching for ie
    //global settings
    $.ajaxSettings.cache = false;
    history.navigationMode = 'compatible';
    
    /*Overlay Call*/
    if(!(BrowserDetect.version == '6'))
    {
        setOverlay('#anchor a.Dates');
    }
	// common overlays
    setOverlay('.linkLayerSii');
    setOverlay('a[rel="#layerBack"]');			// not for aldi
    setOverlay('a[rel="#layerIframe"]');
    setOverlay('a[rel="#lightboxGallery"]');
	// BUM overlays
	setOverlay('#bookingservice a.Dates');
    setOverlay('.buttonHolderLine a.Dates');
	setOverlay('a[rel="#countryInformation"]');
    setOverlay('a[rel="#erab"]');
	// ernstings overlays
	setOverlay('a[rel="#departureDate"]');
    setOverlay('input[rel="#approachKm"]');
    

    //change destination selection
	// @todo: achtung es gibt im header zwei select-felder, die diesen id-namen trage. evlt. sollten diese beiden felder stattdessen einen gemeinsamen klassen-namen bekommen
    $('#destinationSelection select').change(function(){
        if($(this).val() != 0)
            top.location.href = $(this).val();
    });
    $('#themeSelection select').change(function(){
    	if($(this).val() != 0)
    		top.location.href = $(this).val();
    });

    // next step assurance
    $('#serviceExtraButton').click(function(){
    	var checked = false;
    	$('.contentContainerFull input:radio').each(function(){
    		if($(this).attr('checked') == true)
			{
    			checked = true;
			}
    	});
    	if(!checked)
		{
    		alert('Bitte wählen Sie eine Zimmerkombination aus.');
    		
    		return false;
		}
    	
    	return true;
    });
    
    //add bus
    $('#addBus .addBusForm select').change(function(){
        var form = $(this).parents('form');
        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
                var price = $('#addBus .contPrice b');
                price.html(json.price);
                updateShoppingCart();
                var priceFields = $('#addAssurance .priceNum');
                priceFields.eq(0).html(json.priceList.all);
                priceFields.eq(1).html(json.priceList.part);
            }
            else
            {
               //alert(json.errorMsg);
            }
        });
    });
  //add musical
    $('#addMusical .addMusicalForm select').change(function(){
        var form = $(this).parents('form');
        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
            	form.prev('.contPrice').find('b').html(json.price);
                updateShoppingCart();
                var priceFields = $('#addAssurance .priceNum');
                priceFields.eq(0).html(json.priceList.all);
                priceFields.eq(1).html(json.priceList.part);
            }
            else
            {
                alert(json.errorMsg);
            }
        });
        form.find('.usedTicketCode').val($(this).val());
    });

    //add donation
    $('#addDonation .addDonationForm input:radio').click(function(){
        var form = $(this).parents('form');
        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
                form.find('.contPrice').find('b').html(json.price);
                updateShoppingCart();
                var priceFields = $('#addDonation .contPrice');
                priceFields.eq(0).html('<b>' + json.price + '</b>');
            }
            else
            {
                alert(json.errorMsg);
            }
        });           
    });

    //add assurance
    $('#addAssurance .addAssuranceForm input:radio').click(function(){
        var form = $(this).parents('form');
        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
                updateShoppingCart();
            }
            else
            {
                alert(json.errorMsg);
            }
       });

    });
    
    $('#addAssurance .addAssuranceForm input:checkbox').click(function(){
        var form = $(this).parents('form');
        var price = $(this).parent('div').find('.priceNum');
        var retention = $(this).parent('div').find('.retention');

        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
            	updateShoppingCart();
            	price.html(json.price);
            }
            else
            {
            	//alert(json.errorMsg);
            }
        });
        
    });
    deleteLastLine();
    radioCheckW();
    
    //add extra service checkbox
	// IE onchange bug fix
	/*if($.browser.msie) {
		$('#addServiceExtra .addServiceExtraForm input:checkbox').click(function() {
			$(this).change();
		});
	}*/
    $('#addServiceExtra .addServiceExtraForm input:checkbox').change(function(){
        var form = $(this).parents('form');
        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
                updateShoppingCart();
                var priceFields = $('#addAssurance .priceNum');
                priceFields.eq(0).html(json.priceList.all);
                priceFields.eq(1).html(json.priceList.part);
            }
            else
            {
                //alert(json.errorMsg);
            }
        });
    });
    //add extra service select
    $('#addServiceExtra .addServiceExtraForm select').change(function(){
        var form = $(this).parents('form');
        var query = form.attr('action') + '?' + form.serialize();
        $.getJSON(query, function(json){
            if(!json.error)
            {
                updateShoppingCart();
                form.prev('.contPrice').find('b').html(json.price);
                var priceFields = $('#addAssurance .priceNum');
                priceFields.eq(0).html(json.priceList.all);
                priceFields.eq(1).html(json.priceList.part);
            }
            else
            {
                //alert(json.errorMsg);
            }
        });
        form.find('.usedServiceCode').val($(this).val());

    });

//-----------------    Formularfelder Schritt 4 aktualisieren  ------------------
   function transferContactData() {
        if($('#person_firstPersonAsAdult').attr('checked') == true)
        {
            $('#person_adult_0_title').val($('input[name="contact[title]"]').index($(':checked')));
            $('#person_adult_0_firstName').val($('#contact_firstName').val());
            $('#person_adult_0_lastName').val($('#contact_lastName').val());
            $('#person_adult_0_dateDay').val($('#contact_dateDay').val());
            $('#person_adult_0_dateMonth').val($('#contact_dateMonth').val());
            $('#person_adult_0_dateYear').val($('#contact_dateYear').val());
        }
        else
        {
            $('#person_adult_0_title').val(0);
            $('#person_adult_0_firstName').val('');
            $('#person_adult_0_lastName').val('');
            $('#person_adult_0_dateDay').val('');
            $('#person_adult_0_dateMonth').val('');
            $('#person_adult_0_dateYear').val('');
        }
   }

    $('#person_firstPersonAsAdult').click(transferContactData);
    $('#contact_firstName, #contact_lastName').keyup(transferContactData);
    $('input[name="contact[title]"], #contact_birthday select').change(transferContactData);
    
  //-----------------    Formularfelder aktualisieren ende ------------------

	/*Carousel Lite I*/
	$(function() {
        try
        {
    		$("#lightbox").jCarouselLite({
    			btnNext: ".nextCarousel",
    			btnPrev: ".prevCarousel",
    			visible: 4,
    			speed: 800,
    			easing: 'easeInOutQuint'
    		});

        	setOverlay('.carousel #lightbox img');
        } catch (e)
        {
        }
	});

	$('.carousel #lightbox img').click(function() {
		var imgSRCLarge = $(this).attr('src').replace('mini_','xxlarge_');
        var imgSRC = $(this).attr('src');
		
		$('#lightboxGallery .galleria li img').each(function(i){
			$(this).attr('rel',(i+1));
			var imgSrcGal = $(this).attr('src');
			if((imgSRC == imgSrcGal) || (imgSrcGal.indexOf(imgSRC) > 0))
			{
			    $(this).trigger("click");
			    var indexImg = $(this).attr('rel');
			    var countImg = $('#lightboxGallery .galleria li img').length;
			    //alert(indexImg);
			    if((countImg > 5) && (indexImg > 5))
			    {
			    	$('.sliderjs .galleria').css('left',(-99*(indexImg - 5)));
			    }
			    else
			    {
			    	$('.sliderjs .galleria').css('left',0);
			    }
			}
		});
		if($('.carouselImages').length == 0)
		{
	        $('#travelcontent_left div.carousel').after('<div style="display: none;" class="carouselImages"></div>');
	        $('.carousel #lightbox img').each(function(){
	            var imgSRCLargeS = $(this).attr('src').replace('mini_','xxlarge_');
	            $('.carouselImages').append('<img src="'+imgSRCLargeS+'" />')
	        });
		}
	});

	/*galery-View / carousel II*/

    sliderWidth = $('.carousel #lightbox img').length * 99;
        $(".galleria").PikaChoose({
            show_captions: false,
            auto_play: false,
            thumb_width: 88,
            thumb_height: 60
        }); 

    $(".galleria").SliderJS({
        window_width: 484,
        window_height: 64,
        list_width: sliderWidth,
        pikachoose: true
    });
   
	
	/*Article List; show 6*/
	$('.sidebar p a').click(function(){
	    if($(this).hasClass('close')){
            $(this).parents('.SimpleTeaser').find('li.hideLi').each(function(){
                $(this).animate({
                    height: 'hide'
                });
            });
            $(this).parents('.SimpleTeaser').find('p a').html('Alle Anzeigen');
            $(this).removeClass('close');
	    }
	    else
	    {
            $(this).parents('.SimpleTeaser').find('li.hideLi').each(function(){
                $(this).animate({
                    height: 'show'
                });
            });
            $(this).parents('.SimpleTeaser').find('p a').html('verstecken');
            $(this).addClass('close');
	    }
	    
	    return false;
	});
	/**/
	
	//Anfang Qtip2 tooltip
	$('.infoBadgeClass, .tooltip_active').live('mouseover', function(event) {

	var alt = $(this).attr('alt');
	var title = $(this).attr('oldtitle');

	   $(this).qtip({
	   overwrite: false,
	   content: {
	   		text: title,
	   		title: alt
	    },
	    position: {
		    my: 'left center',
		    at: 'right center'
	    },
	    show: {
		    delay: 50,
		    event: event.type,
		    ready: true
	    },
	    style: {
	        tip: {
		        width: 12,
		        height: 20
	        },
	        classes: 'ui-tooltip-blue'
	    }
	}, event);

	})
	.each(function(i) {
	    $.attr(this, 'oldtitle', $.attr(this, 'title'));
	    this.removeAttribute('title');
	});
	//Ende Qtip2 tooltip

	/*Print Sixth Step*/
    $('.bookingNumber .bTextFr a').click(function() {
        window.print();
    });
	
	/*Layer Country Info Show*/
	$('.countryInfoBoxBt a.butPrint').css('display', 'none');
    $('.countryInfoBoxTop select').each(function(){
        $(this).find('option[value="0"]').attr('selected', 'selected');
    });
    
    /*layerIframe*/
    $('a[target=layer]').live('click',function(e){
        if(e.button==0){
            $('#layerIframeLink').trigger('click');
        }
    });
   
    
    $('#travelcontent_left ul li').each(function(){
        if($(this).find('h3').length > 0)
        {
            $(this).css('listStyleType','none');
            $(this).css('background','none');
            $(this).css('paddingLeft','5px');
        }
        if($(this).html() == '')
        {
            $(this).remove();
        }
    });
   

    /*IE7 Bar*/
    function resetBarsIE()
    {
    	var htmlWidth = $('html').attr('clientWidth');
    	var pageWidth = '990';
    	if(htmlWidth < pageWidth)
    	{
    		$('html').attr('style','overflow-x: scroll;');
    	}
    	else
    	{
    		$('html').attr('style','overflow-x: visible;');
    	}
    }
    if((($.browser.msie) && (BrowserDetect.version == '8')) || (($.browser.msie) && (BrowserDetect.version == '7')) && ($('#page').length > 0)) {
    	resetBarsIE();
    	$(window).resize( function() {
    		resetBarsIE();
    	}); 
    }
    
    var urlPage = '"'+window.location+'"';
    if(urlPage.indexOf('#print')>-1)
    {
    	window.print();
    	window.close();
    }

});

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

