$(function()
{
    
    /***************************************
    *************** General ****************
    ****************************************/
    
    $.PATH = $('#PHP_PATH').text();
    
    $('.gallery').fancybox();
    
    $('a[rel=external][href!="javascript:void(0);"]').attr('target', '_blank');
    
    
    /***************************************
    *************** Slider *****************
    ****************************************/
    
    var active = 0;
    var size   = $('#slider .slide').size();
    var speed  = 500;
    var delay  = 7500;
    
    if(size > 1)
    {
        $('#slider .slide').css('opacity', 0).eq(0).css('opacity', 1).css('z-index', 100);

        function slider()
        {
            $('#slider .slide').eq(active).css('z-index', 99).animate({opacity: 0}, speed);
            
            switch(true)
            {
                case (isNaN(active)):
                    active = 0;
                        break;
                case (active > size - 2):
                    active = 0;
                        break;
                default:
                    active++;
            }
            
            $('#slider .slide').eq(active).css('z-index', 100).animate({opacity: 1}, speed);
        }
        
        var interval = setInterval(slider, delay);
    }
    
    /***************************************
    *************** Dialog *****************
    ****************************************/
    
    var noticeContainer = $('div#message');
    var timeout;
    
    function showNotification(notice, stay)
    {
        if(timeout)
        {
            clearTimeout(timeout);
        }
        
        noticeContainer.stop().css('height', 0).show().html(notice).animate({height: 50}, 500).bind('click', hideNotification);
        
        if(!stay)
        {
            timeout = setTimeout(hideNotification, 5000);
        }
    }
    
    function hideNotification()
    {
        noticeContainer.animate({height: 0}, 500, function() { $(this).hide(); }).unbind('click');
        clearTimeout(timeout);
    }

    if(noticeContainer.text() != "")
    {
        showNotification(noticeContainer.html());
    }
    
    /***************************************
    *************** Contact ****************
    ****************************************/
    
    $('form#contact').not('.rentForm').submit(function()
    {
        var errorCount = 0;
        var wrongEmail = false;
        
        $('input.text, textarea', this).each(function()
        {
            if($.trim($(this).val()) == '')
            {
                errorCount++;
            }
            
            if($(this).attr('name').toLowerCase() == 'email')
            {
                if(!/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/.test($.trim($(this).val())))
                {
                    wrongEmail = true;
                    errorCount++;
                }
            }
        });
        
        if(errorCount < 1)
        {
            return true;
        }
        else
        {
            showNotification(wrongEmail && errorCount == 1 ? 'O email digitado é inválido.' : 'Preencha todos os campos.');
            return false;
        }
    });
    
    /***************************************
    **************** Frota *****************
    ****************************************/
    
    $('.openFleet').click(function(e)
    {
        e.preventDefault();
        
        $.get('index.php', { ajax: 'fleet', fleet: $(this).attr('href').split('|').reverse()[0] }, function(response)
        {
            if(response.error)
            {
                showNotification(response.error);
            }
            else
            {
                $.fancybox(response.images, {
                    type: 'image',
                    cyclic: true
                });
            }
        },
        'json');
    });

    $('#searchForm').submit(function()
    {
        if($('select[name="from"]').val() === $('select[name="to"]').val())
        {
            showNotification('Destino inválido.');
            return false;
        }

        return true;
    });
    
    //$('.embrace').eq(0).show();
    
    $('h2').click(function()
    {
        $(this).next('.embrace').toggle('slow');
    });
    
    $('#link-lines a:last').css('margin', 0);
    
    $('#link-lines a, .search-link').click(function(e)
    {
        e.preventDefault();
        
        var customForm = document.createElement('form');
        customForm.action = '?form=search';
        customForm.method = 'post';
        
        var line = document.createElement('input');
        line.type = 'hidden';
        line.name = 'line';
        line.value = $(this).attr('line');
        
        var from = document.createElement('input');
        from.type = 'hidden';
        from.name = 'from';
        from.value = $(this).attr('from');
        
        var to = document.createElement('input');
        to.type = 'hidden';
        to.name = 'to';
        to.value = $(this).attr('to');
        
        customForm.appendChild(line);
        customForm.appendChild(from);
        customForm.appendChild(to);
        
        document.body.appendChild(customForm);
        
        customForm.submit();
    });
    
    function changeOptions(i)
    {
        var place = $('select[name="from"], select[name="to"]').empty();
        var element;
        
        if(storedDestinations[i])
        {
            for(var j in storedDestinations[i])
            {
                element = document.createElement('option');
                element.value = j;
                element.appendChild(document.createTextNode(storedDestinations[i][j]));
                place.append(element);
            }
        }
    }
    
    $('#lines input:radio').click(function()
    {
        changeOptions($(this).val());
    });
    
    $('a.printPage').click(function(e)
    {
        e.preventDefault();
        
        window.print();
    });
    
    if(actualDestinations)
    {
        changeOptions(actualDestinations.line);
        $('#lines input:radio').attr('checked', false).filter('[value="' + actualDestinations.line + '"]').attr('checked', 'checked');
        $('select[name="from"] option[value="' + actualDestinations.from + '"]').attr('selected', true);
        $('select[name="to"] option[value="' + actualDestinations.to + '"]').attr('selected', true);
    }
    
});

