var do_not_restore_from_cookie = false;

$(function(){

    /**
     * Init
     */
    
    $("#searchForm1").cacheInCookie();
    $("#searchForm1").submit(function(){
        $("#hfd").val( $("#hfd").val() / 1000 );
        $("#htd").val( $("#htd").val() / 1000 );
        $("#all_destinations, #all_airports, #child-selector").parent().appendTo($("form:first"));
    })

    /**
     * Autocompleter
     */
    var data_destinations = new Array();
    $("#destination").attr("size","26").find("option").each(function(a,i){
        data_destinations.push({label: $(i).text(), value: $(i).val()});
    });

    var data_airports = new Array();
    $("#abflug").attr("size","26").find("option").each(function(a,i){
        data_airports.push({label: $(i).text(), value: $(i).val()});
    });

    $("input#destination_label").focus(function(e){$(this).select();}).autocomplete(data_destinations,{
        minChars: 2,
        multiple:false,
        matchContains: "word",
        autoFill: false,
        width: "284px",
        formatItem: function(row, i, max) {
            return row.label;
        },
        formatMatch: function(row, i, max) {
            return row.label + " " + row.value;
        },
        formatResult: function(row) {
            return row.label;
        }
    });

    $("#destination_label").result(function(event, data, formatted) {
        if (data) {
            $("select#destination option[value='"+data.value+"']").attr('selected', 'selected');
        }
    });

    $("input#abflug_label").focus(function(e){$(this).select();}).autocomplete(data_airports,{
        minChars: 2,
        multiple:false,
        matchContains: "word",
        autoFill: false,
        width: "284px",
        formatItem: function(row, i, max) {
            return row.label;
        },
        formatMatch: function(row, i, max) {
            return row.label + " " + row.value;
        },
        formatResult: function(row) {
            return row.label;
        }
    });
    $("#abflug_label").result(function(event, data, formatted) {
        if (data) {
            $("select#abflug option[value='"+data.value+"']").attr('selected', 'selected');
        }
    });

    /**
     * Dialogs
     */
    $("#all_destinations, #all_airports").find("select").dblclick(function(){
        $(this).parent().dialog('close');
    });
    $("#all_destinations").dialog({
        autoOpen: false,
        modal:true,
        width: '320px',
        buttons: {
            'Abbrechen': function() {
                $(this).dialog('close');
            },
            'OK': function() {
                $(this).dialog('close');
            }
        },
        close: function(){
            // updating html
            var val     = $(this).find("select").val();
            var label   = $(this).find("select :selected").text();
            $("#destination_label").val(label);

        }
    });

    $("#button_destination").click(function(event){
        var pos = MyFormUtils.getCustomPosition(event.target);
        $("#all_destinations").dialog('option',{
            open: function(event, ui){
                //$("#all_destinations").parent().appendTo($("form:first"));
                $("#all_destinations").dialog('option',{
					// Geändert - DJ - 2010-05-18
					//'position': [pos.left, pos.top]
					'position': [pos.layerX,pos.layerY]
                });
            }
        }).dialog('open');
    });
    $("#all_airports").dialog({
        autoOpen: false,
        modal:true,
        width: '320px',
            buttons: {
            'Abbrechen': function() {
                $(this).dialog('close');
            },
            'OK': function() {
                $(this).dialog('close');
            }
        },
        close: function(){
            // updating html
            var val     = $(this).find("select").val();
            var label   = $(this).find("select :selected").text();
            $("#abflug_label").val(label);

        }
    });

    $("#button_abflug").click(function(event){
        if (typeof(button_abflug_disabled) != "undefined" && button_abflug_disabled ) return false;
        var pos = MyFormUtils.getCustomPosition(event.target);
        $("#all_airports").dialog('option',{
            open: function(event, ui){
                //$("#all_airports").parent().appendTo($("form:first"));
                $("#all_airports").dialog('option',{					  
                    // Geändert - DJ - 2010-05-18
					//'position': [pos.left, pos.top]
					'position': [pos.layerX,pos.layerY]
                });
            }
        }).dialog('open');
        return false;
    });

    $("#child-selector").dialog({
        autoOpen: false,
        modal:true,
        width: "220px",
        buttons: {
            'O.K.': function() {
                $(this).dialog('close');
            },
            'Keine Kinder': function() {
                var allFields = $([]).add("#cd1").add("#cd2").add("#cd3");
                var allHidden = $([]).add("#c1").add("#c2").add("#c3");
                allFields.val('');
                allHidden.remove();
                $(this).dialog('close');
            }
        },
        close: function(){
            // updating html
            var allVals = new Array();
            if ($("#cd1").val() != "")  allVals.push($("#cd1").val() );
            if ($("#cd2").val() != "")  allVals.push($("#cd2").val() );
            if ($("#cd3").val() != "")  allVals.push($("#cd3").val() );

            var string="";
            var el = this;
            $(allVals).each(function(a,i){
                t = a+1;
                if (a==allVals.length-1 && a>0) string +=" und ";
                else if (a >0) string +=",";
                if (i==1) string +="<2";
                else string += i;
            });
            if (allVals.length>0)string += " Jahre";
            $(".childs .readable").text(string);
            $("#child-selector").parent().appendTo($("form:first"));

        }
    });

    //$("#child-selector, #all_destinations, #all_airports").dialog('close');
    var clicked = false;
    $(".childs").click(function(event){
        var pos = MyFormUtils.getCustomPosition(event.target);

        /*
         * Date: 01.07.2010
         * Author: Martin Hauck
         * Email: mh@reise.com
         * Comment: quick and dirty fix
         */
        var px = 0;
        var py = 0;
        if(clicked == true)
        {
            px = 10;
            py = 10;
        }
        else
        {
            clicked = true;
            px = pos.layerX;
            py = pos.layerY;
        }

        $("#child-selector").dialog('option',{
            open: function(event, ui){
                //$("#child-selector").parent().appendTo($("form:first"));
                $("#child-selector").dialog('option',{
					// Geändert - DJ - 2010-05-18
					//'position': [pos.left,pos.top]
					'position': [px,py]
                });
            }
        }).dialog('open');
        return false;
    });
    //$("#all_destinations, #all_airports, #child-selector").parent().appendTo($("form:first"));


    /**
     * Datepicker
     */
    $.datepicker.setDefaults($.datepicker.regional['de']);

    $('#fromdate, #todate').change(function(){
        var d = Date.parse($(this).val());
        if ($(this).datepicker('getDate').getTime() !== d.getTime() ) {
            $(this).datepicker('setDate', d);
        }
        $(this).blur();
    });

    var s_tdv = ( $("#htd").val()*1 >= 10000000000 ) ?$("#htd").val()*1 : $("#htd").val()*1000;
    var s_fdv = ( $("#hfd").val()*1 >= 10000000000 ) ?$("#hfd").val()*1 : $("#hfd").val()*1000;

    $('#fromdate, #todate').datepicker({
        showAnim: "fadeIn",
        showOn: 'both',
        changeMonth: true,
        numberOfMonths: 2,
        showWeek: true,
        minDate: '+2',
        maxDate: '+11M +10D',
        dateFormat: "D, dd.mm.yy",
        buttonImage: '/images/cal2.gif',
        buttonImageOnly: true,
        buttonText: 'Kalender anzeigen',
        beforeShow: MyFormUtils.customRange,
	onSelect: MyFormUtils.checkDate,
        altFormat: '@'
    });
    $('#fromdate').datepicker('option', 'altField', '#hfd');
    $('#todate').datepicker('option', 'altField', '#htd');

    if (s_tdv > 0 ) {
        $("#todate").datepicker('setDate', new Date(s_tdv) );
    }
    if (s_fdv > 0 ) {
        $("#fromdate").datepicker('setDate', new Date(s_fdv) );
    }

    $(".custom_search input[type='radio']").prettyCheckboxes({
        checkboxWidth: 22, // The width of your custom checkbox
        checkboxHeight: 20, // The height of your custom checkbox
        className : 'prettyCheckbox', // The classname of your custom checkbox
        display: 'inline' // The style you want it to be display (inline or list)
    });

    $("#duration").styledSelect();
    $("#searchForm1").show();

    /**
     * Changer
     */
    $("input[name='booktype']").change(function(){
        var type = $(this).val();
        if(type=='eigenanreise' || type=='ferienhaus') {
            $('#abflug, #abflug_label').attr("disabled", true).addClass("disabled");
            $("#all_airports").dialog('disable');
            button_abflug_disabled = true;
            $("#button_abflug").addClass('disabled');
        } else {
            $('#abflug, #abflug_label').removeAttr("disabled").removeClass("disabled");
            $("#all_airports").dialog('enable');
            button_abflug_disabled = false;
            $("#button_abflug").removeClass('disabled');
        }
        var arrSettings = [];
        arrSettings['storage'] = type;
        alert(arrSettings['storage']);

        $('#typelink').attr('href','/'+type);
        $('#searchForm1').attr('storage', type);
        $('#searchForm1').attr('action', '/'+type+'/result');

        $('form').cacheInCookie(arrSettings);
    })

    $(".reset_form").click(function(){
        $('form').cacheInCookie.destroy();
        window.location.reload();
    })
    $("#duration").trigger('change');
});