// Requires jQuery >= 1.3.2. Not yet tested with jQuery >= 1.4

jQuery(function($)
{
    // define url for ajax requests (prepend full hostname because relative urls get prefixed by host defined in <base href> which is zws-online.de, 
    // so our ajax requests would be blocked on zwsonline.de due to cross-domain security restrictions!)
    var ajaxRequestUrl = document.location.protocol + '//' + document.location.hostname + (document.location.port ? ':' + document.location.port : '')
                       + '/index.php?id=' + tx_tarifrechner_pi1_jsOptions.pageId + '&type=' + tx_tarifrechner_pi1_jsOptions.ajaxPageTypeNum;

    var currentAjaxRequest = null;
    
    $(document).ajaxSend(function()
    {
        $('.tx-tarifrechner-pi1').block({
            message: null, // FIXME schöne "Bitte warten" animation. allerdings war die platzierung bei meinen tests zufällig, das ist nicht so schön. daher erst einmal ohne message.
            overlayCSS: {
                backgroundColor: '#fff',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px'
            },
            applyPlatformOpacityRules: false,
            centerX: true,
            centerY: true,
            fadeIn:  100,  // fadeIn time in millis; set to 0 to disable fadeIn on block
            fadeOut: 250  // fadeOut time in millis; set to 0 to disable fadeOut on unblock
        });
    });
    
    // Unblock when AJAX activity stops
    $(document).ajaxStop(function()
    {
        $('.tx-tarifrechner-pi1').unblock();
    });
 
    
    var ajaxDelay = 1000; //ms. Time a AJAX request is delayed.
    
    function postpone(f)
    {
        if (f._zws_tr_postponedTimer)
        {
            clearTimeout(f._zws_tr_postponedTimer);
        }
        f._zws_tr_postponedTimer = setTimeout(f, ajaxDelay);
    }

    function postponed(f)
    {
        return function()
        {
            postpone(f);
        }
    }
    
    function searchLocation(field)
    {
        var otherField = (field == 'tr_start') ? 'tr_ziel' : 'tr_start';
        
        var data = $('#' + field).val();
        if (data.length == 0)
        {
            $('#' + field + '_popup_box').hide();
        }
        else
        {
            if (currentAjaxRequest) currentAjaxRequest.abort();
            currentAjaxRequest = $.post(
                ajaxRequestUrl,
                {
                    tr_ajax:  'search-location',
                    tr_query: data,
                    tr_field: field
                }, function(result)
                {
                    if (result.length > 0)
                    {
                        $('#' + field + '_locations').html(result);
                        
                        $('#' + field + '_popup_box').show();
                        $('#' + otherField + '_popup_box').hide();
                    }
                }
            );
        }
    }
    
    function setLocation(field, data)
    {
        $('#' + field).val(data);
        if (data && data.length)
        {
            $('#' + field + '_results').html('');
            reloadForm();
        }
        else
        {
            resetLocation(field);
        }
        $('#' + field + '_popup_box').fadeOut(350);
    }
    
    function resetLocation(field)
    {
        $('#' + field + '_locations').html('<p class="tr_nosearch">Bitte geben Sie einen Ort oder eine Haltestelle an.</p>');
    }
    
    function initForm()
    {
        /* general form stuff
           ------------------ */
        
        // hide submit button (required only as fallback if JavaScript is disabled)
        $('#tr_submit').hide();
        
        // prevent regular form submission (replace by AJAX lite, see reloadForm())
        $('#tr_form').bind('submit', function()
        {
            return false;
        });
        
        
        /* tariff info buttons and boxes
           ----------------------------- */
           
        // tariff info buttons open tariff info boxes and do not open tariff info in new window (= disable non-js fallback)
        $('.tariffinfo-button').bind('click', function(ev)
        {
            ev.preventDefault();
        }).show();
        /* FIXME-TARIFFINFO-NONJS: remove show() as soon as non-JS fallback (info in new window) works flawlessly */


        // activate foldable tarriff infoboxes (bind to whole ticket rows, not only to info buttons)
        $('.pricelist-item-ticket').bind('click', function(ev)
        {
            $(this).find('.tariffinfo-content').slideToggle(750);
        });
        
        /* ------------- */
           
        // turn off browser autocompletion for these fields
        $('#tr_start, #tr_ziel, #tr_cnte, #tr_cntk').attr('autocomplete', 'off');
    

        // workaround for false "change" event handling by IE for radio buttons and checkboxes
	// see http://norman.walsh.name/2009/03/24/jQueryIE and
	// http://www.quirksmode.org/dom/events/change.html
        if ($.browser.msie)
        {
            $('input:radio,input:checkbox').bind('click', function()
	    {
	        this.blur();
                this.focus();
            });
        }

        $('#tr_fieldset_typ input[type=radio]')
            .add('#tr_fieldset_optionen input[type=checkbox]')
	    .bind('change', reloadForm);
    
        $('#tr_cnte, #tr_cntk').bind('keyup', postponed(reloadForm));
        
        $('a.tr_clearfield').bind('click', function()
        {
            var field = $(this).attr('rel');
            resetLocation(field);
            $('#' + field).val('');
            $('#tr_result').html('');
            return false;
        }).show();
        
        $('#tr_start, #tr_ziel').each(function()
        {
            var elem = this; // write this into variable because we need the value in postponed callback
            $(elem)
                .bind('keyup', postponed(function(){searchLocation(elem.id)}))
                ;//.bind('blur', function(){setLocation(elem.id)}); // FIXME brauchen wir das?
        });
        
        $('.count-decr, .count-incr').bind('click', function()
        {
            var $input = $(this).closest('label').find('input[type=text]');
            var value = parseInt($input.val(), 10);
            value = (isNaN(value)) ? 0 : value;
            var newValue = Math.max(0, value + ($(this).hasClass('count-decr') ? -1 : 1));
            if (newValue != value)
            {
                $input.val(newValue);
                postpone(reloadForm);
            }
        }).show();

        // focus first required form field which is empty
        // NICE: tr_start and tr_ziel may not be empty but don't define a valid start or destination. they should be considered empty in that case, aswell!
        var fieldIds = ['tr_start', 'tr_ziel'];
        $.each(fieldIds, function()
        {
            var $field = $('#' + this);
            if (!$.trim($field.val()).length)
            {
                $field.focus();
                return false;
            }
        });
    }

    // "cheap" ajax form submit (was previously a full page submit)
    function reloadForm()
    {
        var $form = $('#tr_form');
        if (currentAjaxRequest) currentAjaxRequest.abort();
        currentAjaxRequest = $.post(
            ajaxRequestUrl,
            $form.serialize() + '&tr_ajax=submit-form',
            function(data, textStatus)
            {
                $(data).find('#tr_form').replaceAll($form);
                $(data).find('#tr_log').replaceAll($('#tr_log'));
                initForm();
            }
        );
    }

    $('.tx-tarifrechner-pi1').bind('click', function(ev)
    {
        var $target = $(ev.target);
        var $li = $target.closest('.tr_searchlocation_results li');
        if ($li.length)
        {
            var area = $li.closest('.tr_popup_box').prevAll('input[type=text]').eq(0).attr('id');
            
            var href = $li.find('a').attr('href');
            var url = $.url.parse(href);
            var text = url.params['tx_tarifrechner_pi1'][area];
            
            setLocation(area, text);
            
            // do not follow links (these are used as non-JS fallback, for JS we have
            // the click logic bound to lis, see above in this function)
            ev.preventDefault();
        }
    });

    initForm();
});


