(function($) {
    /* offset fix for mobile safari */
    if ( /webkit.*mobile/i.test(navigator.userAgent)) {
        (function($) {
            $.fn.offsetOld = $.fn.offset;
            $.fn.offset = function() {
                var result = this.offsetOld();
                result.top -= window.scrollY;
                result.left -= window.scrollX;
                return result;
            };
        })(jQuery);
    }

    /* German initialisation for the jQuery UI date picker plugin. */
    /* Written by Milian Wolff (mail@milianw.de). */
    $.datepicker.regional['de'] = {
        closeText: 'schließen',
        prevText: '&#x3c;zurück',
        nextText: 'Vor&#x3e;',
        currentText: 'heute',
        monthNames: ['Januar','Februar','März','April','Mai','Juni',
        'Juli','August','September','Oktober','November','Dezember'],
        monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dez'],
        dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
        dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
        dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
        weekHeader: 'Wo',
        dateFormat: 'dd.mm.yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional[ dateRegion ]);

    /* styleswitch js/nojs */
    document.write(
        "<style>"+
        "#error-js-disabled{display: none;}"+
        ".booking-content{display: block;}"+
        "<\/style>"
    );

    /* folding */
    var getFoldConf = function(s) {
        var conf = $(s).data('xwk.fold');
        if (!conf) {
            var c = $(s).height();
            $(s).find('.groupcontentdesc').css({marginTop: -30});
            var h = $(s).css({height: 'auto'}).height();
            conf = {inited:true,h:h,isfolded:true};
            $(s).find('.groupcontentdesc').css({marginTop: 0});
            $(s).height(c).data('xwk.fold',conf);
        }
        return conf;
    }

    $('#main_content .foldable .grouptitle').live(
        'click',function(e){
            var conf = getFoldConf($(this).parent());
            conf.isfolded = !conf.isfolded;
            $(this).css({backgroundPosition: conf.isfolded ? "-10px -40px" : "-10px -70px"});
            $(this).parent().animate({height: conf.isfolded ? 15 : conf.h});
            $(this).parent().find('.groupcontentdesc').animate({marginTop: conf.isfolded ? 0 : -30});
        }
    ).live(
        'mouseover',function(e){
            var conf = getFoldConf($(this).parent());
            $(this).css({cursor: 'pointer', backgroundPosition: conf.isfolded ? "-10px -40px" : "-10px -70px"});
        }
    ).live(
        'mouseout',function(e){
            var conf = getFoldConf($(this).parent());
            $(this).css({backgroundPosition: conf.isfolded ? "-10px -10px" : "-10px -70px"});
        }
    );/*
    $('#main_content .foldable').live(
        'mouseover',function(e){
            var conf = getFoldConf(this);
            conf.isfolded = false;
            $(this).stop().animate({height: conf.isfolded ? 15 : conf.h});
        }
    ).live(
        'mouseout',function(e){
            var conf = getFoldConf(this);
            conf.isfolded = true;
            $(this).stop().animate({height: conf.isfolded ? 15 : conf.h});
        }
    );*/


})(jQuery);

jQuery(function($) {

    /* triptype change */
    $('input[name=triptype]').change(function() {
        if ($(this).val() == 'oneway') {
            $('.direction-img').removeClass('roundtrip');
            $('.direction-img').addClass('oneway');
            $('#transfer-select-oneway-desc').addClass('active');
            $('#transfer-select-roundtrip-desc').removeClass('active');
            $('.desc-roundtrip').slideUp();
            $('#typereturn').slideUp();
        } else {
            $('.direction-img').removeClass('oneway');
            $('.direction-img').addClass('roundtrip');
            $('#transfer-select-roundtrip-desc').addClass('active');
            $('#transfer-select-oneway-desc').removeClass('active');
            $('.desc-roundtrip').slideDown();
            $('#typereturn').slideDown();
        }
    });


    /* payment change */
    $('input[name=payment]').change(function() {
        $('input[name=payment]').each(function(){
            $('label[for='+$(this).attr('id')+']')[this.checked ? "addClass" : "removeClass"]('active');
        });
    });
    $('input[name=payment]:first').change();

    /* transfermode change */
    $('#transfermode-to-destination').change(function () {
        $('#transfermode-to-destination-desc').addClass('active');
        $('#transfermode-to-airport-desc').removeClass('active');
        jtdesc = $('#journeytime-desc').text();
        rtdesc = $('#returntime-desc').text();
        $('#journeytime-desc').text(rtdesc);
        $('#returntime-desc').text(jtdesc);
    });
    $('#transfermode-to-airport').change(function () {
        $('#transfermode-to-airport-desc').addClass('active');
        $('#transfermode-to-destination-desc').removeClass('active');
        jtdesc = $('#journeytime-desc').text();
        rtdesc = $('#returntime-desc').text();
        $('#journeytime-desc').text(rtdesc);
        $('#returntime-desc').text(jtdesc);
    });

    $('.direction-from-airport').click(function() {
        $('input[id=transfermode-to-destination]').attr('checked', true);
        $('input[id=transfermode-to-airport]').attr('checked', false);
        $('#transfermode-to-destination').change();
    });
    $('.direction-to-airport').click(function() {
        $('input[id=transfermode-to-destination]').attr('checked', false);
        $('input[id=transfermode-to-airport]').attr('checked', true);
        $('#transfermode-to-airport').change();
    });

    /* journey/return datepickers */
    $('.datepicker').datepicker({
        numberOfMonths: 1,
        minDate: 0
    });

    /* autosuggest city */
    var setCityError = function() {
        $('#city-na-error p strong').text($("input[name=destination]").val());
        $('#city-na-error').slideDown();
    }
    var requestcount = 0;
    $('input[name=destination]').data('currentCity', -1);
    $("input[name=destination]").autocomplete({
        minLength: 0,
        source: function(request, response) {
            $('input[name=destination]').data('currentCity', null);
            $('input[name=destinationid]').val(0);
            var requestid = ++requestcount;
            $.getJSON(window.location.href, {
                ap: $("select[name=airport]").val(),
                q: $("input[name=destination]").val(),
                limit: 10,
                ajax: 1,
                ajax_func: $('#suggest_class').val()
            }, function (data, textStatus, xhr) {
                if (requestid != requestcount) {
                    return;
                }
                if (data.length < 1) {
                    setCityError();
                } else {
                    $('input[name=destination]').data('currentCity', data[0]);
                    $('input[name=destinationid]').val(data[0].id);
                    $('#city-na-error').hide();
                }
                response(data, textStatus, xhr);
            });
        },
        select: function (event, ui) {
            $('input[name=destination]').data('currentCity', ui.item);
            $('input[name=destinationid]').val((ui.item) ? ui.item.id : 0);
        }
    });

    // disable city search if no airport is selected
    $('input[name=destination]').each(function() {
        if ($('select[name=airport]').val() == "0") {
            $(this).addClass('disabled');
            $(this).attr('disabled', 'disabled');
            $('input[name=destination_tooltipdummy]').attr('disabled', 'disabled');
            $('input[name=destination_tooltipdummy]').addClass('disabled');
        }
    });

    // validate city
    $("input[name=destination]").blur(function() {
        var city = $(this).data('currentCity');
        if (city != null) {
            $('#city-na-error').slideUp();
            if (city != -1) {
                $('input[name=destination]').val(city.value);
                $('input[name=destinationid]').val(city.id);
            }
        } else {
            setCityError();
            $('input[name=destinationid]').val(0);

        }
    });

    // select airport
    $("select[name=airport]").change( function() {

        // enable city search on select
        if ($(this).val() != "0") {
            $('input[name=destination]').removeClass('disabled');
            $('input[name=destination]').attr('disabled', null);
            $('input[name=destination_tooltipdummy]').removeClass('disabled');
            $('input[name=destination_tooltipdummy]').attr('disabled', null);
        } else {
            $('input[name=destination]').addClass('disabled');
            $('input[name=destination]').attr('disabled', 'disabled');
            $('input[name=destination_tooltipdummy]').addClass('disabled');
            $('input[name=destination_tooltipdummy]').attr('disabled', 'disabled');
        }

        $.getJSON(window.location.href, {
                ap: $("select[name=airport]").val(),
                q: $("input[name=query]").val(),
                limit: 10,
                ajax: 1,
                ajax_func: $('#suggest_class').val()
            },
            function(data) {
                if (data.length < 1) {
                    $("input[name=destination]").val('').blur();
                }
            });
    });


    /* inputtooltip */
    $('input.inputtooltip[alt]').each(function() {
        var i = $(this);
        var text = i.attr('alt');
        var dummy = $('<input type="text">');
        dummy.attr('class', i.attr('class'));
        dummy.attr('style', i.attr('style'));
        dummy.attr('disabled', i.attr('disabled'));
        dummy.attr('name', i.attr('name') + '_tooltipdummy');
        dummy.val(text);
        i.after(dummy);
        dummy.hide();

        dummy.focus(function() {
            i.show();
            dummy.hide();
            i.focus();
        });

        i.blur(function() {
            if (i.val() == "") {
                i.hide();
                dummy.show();
            }
        });

        i.blur();
    });

    /* return datepicker must be set greater than journey date */
    $('#journey-date-dp').change(function() {
        $('#return-date-dp').datepicker("option","minDate",
            $('#journey-date-dp').datepicker("getDate"));
    });
    $('#return-date-dp').change(function() {
        jd = $('#journey-date-dp').datepicker("getDate");
        rd = $('#return-date-dp').datepicker("getDate");
        if (jd > rd) {
            $('#return-date-error').show();
        } else {
            $('#return-date-error').hide();
        }
    });

    /* offer select */
    $('.offer').click(function(e) {

        var offers = $(this).parent().find('.offer');
        var type = $(this).parent().parent().attr('id');
        var input = $(this).find('input');

        // get realprice of value
        var realprice = function(text) {
            var Expr = /([0-9,\.]+)/;
            Expr.exec(text);
            var t = RegExp.$1;
            return Number(t.split(delimiters.thousand).join("").split(delimiters.comma).join("."));
        }

        var formatPrice = function(price) {
            var t = price.toFixed(2).split(".").join(delimiters.comma);
            if (t.length > 6) {
                t = t.substr(0, t.length - 6) + delimiters.thousand + t.substr(t.length - 6);
            }
            return t;
        }

        // calculate price
        var calculatePrice = function() {
            var journeyOffer = $('#journeyoffers input:checked').parent().parent();
            var returnOffer = $('#returnoffers input:checked').parent().parent();
            var journeyPrice = realprice(journeyOffer.find('.price').text());
            var retPrice = realprice(returnOffer.find('.normprice').text());
            var rabatt = realprice(returnOffer.find('.rabatt').text());

            // do we get a rabatt?
            if (returnOffer.find('.rabatt').hasClass(journeyOffer.find('input').attr('class'))) {
                retPrice = retPrice - rabatt;
            }

            $('#price_journey').text(formatPrice(journeyPrice) + ' EUR');
            $('#price_return').text(formatPrice(retPrice) + ' EUR');
            if ($('#price_return').length > 0) {
                total = journeyPrice + retPrice;
            } else {
                total = journeyPrice;
            }
            $('#price_total').text(formatPrice(total) + ' EUR');

        }

        offers.find('input').each(function() {
            this.checked = false;
        });
        input.each(function() {
            this.checked = true;
        });


        offers.removeClass('active');
        $(this).addClass('active');

        // journey
        if (type == 'journeyoffers') {
            // change rabatt
            $('.rabatt').hide();
            if (0 < realprice($('.rabatt.' + input.attr('class')).text())) {
                $('.rabatt.' + input.attr('class')).show();
            }
        }

        calculatePrice();
    });

    // show first rabatt
    $('#journeyoffers input:checked').click();
    $('#returnoffers input:checked').click();

    // show checktime popup window 
    var popwin = $('.time-not-set-dialog > .wrapper');
    var showSetTimePopup = function() {
    	var ret = popwin.find('#typereturn'); 
    	ret.css({display: 'block'});
    	if (!roundtrip) {
    		ret.css({display: 'none'});
    	}
    	popwin.dialog({
    		modal: true,
    		title: popup_title_set_flighttime,
    		width: 500,
    		height: (roundtrip == true) ? 150 : 130,
    		resizable: false
    	});
    }
    var submit = $('.button-panel > .show-popup');
    if (submit.length > 0){
	    submit.click(function(e) {
	    	var showPopup = false;
	    	$('#returnoffers > tbody > tr').each(function() {
	    		if ($(this).find('> td > input').attr('checked') && $(this).hasClass('checktime')) {
	    			showPopup = true;
	    		}
	    	});
	    	$('#journeyoffers > tbody > tr').each(function() {
	    		if ($(this).find('> td > input').attr('checked') && $(this).hasClass('checktime')) {
	    			showPopup = true;
	    		}
	    	});
	    	
	    	if (showPopup) {
		    	e.preventDefault();
		    	showSetTimePopup();
		    	return false;
	    	}
	    });
    }
    var validateSetTimePopup = function() {
    	var journey = $('#typejourney').find('.input');
    	var valid = true;
    	journey.each(function() {
    		if ($(this).val() == -1) {
    			valid = false;
    			return false; 
    		}
    	});
    	if (roundtrip) {
    		var returntrip = $('#typereturn').find('.input');
    		returntrip.each(function() {
    			if ($(this).val() == -1) {
    				valid = false;
        			return false; 
        		}
        	});
    	}
    	if (valid) {
    		journey.each(function() {
    			var c = $(this).clone(true, true);
    			c.val($(this).val());
    			$('.time-not-set-dialog').append(c);
    		});
    		
    		if (roundtrip == true) {
    			returntrip.each(function() {
    				var c = $(this).clone(true, true);
    				c.val($(this).val());
    				$('.time-not-set-dialog').append(c);
    			});
    		}
    	}
    	return valid;
    }
    
    popwin.find('.button-next').click(function() {
    	if (!validateSetTimePopup()) {
    		$('#popup-booking-error').css({display: 'block'});
    		return false;
    	}
    	$('#popup-booking-error').css({display: 'none'});
    	$('form').submit();
    });
    
    // infotext dialog
    $('a.info').click(function() {
        var service = $('#infotext_' + $(this).attr('rel'));
        if (service.attr('title') != null) {
            service.attr('title', service.find('h1:first').text());
            service.find('h1:first').remove();
        }
        service.dialog({
            modal: true
        });
    });

    // pointer to submit buttons
    $('input[type=submit]').css('cursor', 'pointer');
    
});

