var currentFocus;

var removeNonIEProps = function(obj) {
    if (jQuery.browser.msie) {
        delete obj['MozBoxShadow'];
        delete obj['textShadow'];
    }
    return obj;
}
var ui =
{
    map:
    {
        header: 
        {
            localization:
            {
                changeState: function(e)
                {
                    var $el     = $(e.currentTarget);
                    var $checked= $('#localization :checked ~ abbr');
                    var type    = e.type;

                    switch( type )
                    {
                        case 'mouseenter':
                            if($el.attr('title') != $checked.attr('title')){
                                $el.stop().animate(
                                removeNonIEProps({ 
                                    backgroundColor: '#e2e2e2',
                                    color: '#000',
                                    borderColor: '#222',
                                    MozBoxShadow: '0 0 3px 1px #000, 0 0 3px 2px #aaa inset, 0 5px 3px 1px #bbb inset',
                                    textShadow: '0 0 0 #fff'
                                }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });
                            }
                        break;

                        case 'mouseleave':
                            $('#localization input ~ abbr').stop().animate(
                            removeNonIEProps({ 
                                backgroundColor: '#5a5a5a',
                                color: '#d6d6d6',
                                borderColor: '#000',
                                MozBoxShadow: '0 0 3px 1px #000, 0 0 3px 2px #333 inset, 0 0 3px 2px #333 inset'
                            }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });
                            
                            $('#localization :checked ~ abbr').stop().animate(
                            removeNonIEProps({ 
                                backgroundColor: '#9bdc49',
                                color: '#fff',
                                borderColor: '#b6e470',
                                MozBoxShadow: '0px 0px 3px 1px #6da430, 0px 2px 2px 3px #b6e470 inset, 0px -4px 2px 3px #6da430 inset',
                                textShadow: '0 0 3px #000'
                            }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });
                            
                        break;
                        
                        case 'click':
                            $('#localization input ~ abbr').stop().animate(
                            removeNonIEProps({ 
                                backgroundColor: '#5a5a5a',
                                color: '#d6d6d6',
                                borderColor: '#000',
                                MozBoxShadow: '0 0 3px 1px #000, 0 0 3px 2px #333 inset, 0 0 3px 2px #333 inset'
                            }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });

                            $el.stop().animate(
                            removeNonIEProps({ 
                                backgroundColor: '#9bdc49',
                                color: '#fff',
                                borderColor: '#b6e470',
                                MozBoxShadow: '0px 0px 3px 1px #6da430, 0px 2px 2px 3px #b6e470 inset, 0px -4px 2px 3px #6da430 inset',
                                textShadow: '0 0 3px #000'
                            }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });

                        break;

                    }
                },
                
                inputText: function(e)
                {
                    var $el     = $(e.currentTarget);
                    var $title  = $('#route h2 span');
                    var type    = e.type;
                    var equation = jQuery.browser.msie ? 'linear' : 'easeOutBack'; //believe it or not, ie will screw it up cz 'back' will set it to a negative value;
                    switch(type)
                    {
                        case 'mouseenter':
                            //$title.animate({ color: '#ccc' , textShadow: '0 0 2px #aaa' }, { duration: 200 , easing: 'linear', queue: false, complete: function(){}});
                        break;
                        
                        case 'mouseleave':
                            var cId = $(currentFocus).attr('id') || '';
                            if(cId != 'route-from' && cId != 'route-to') {
                                //alert(cId);
                                //$title.animate({ color: '#9BDC49' , textShadow: '0 0 2px #9BDC49' }, { duration: 200 , easing: 'linear', queue: false, complete: function(){}});
                            }
                        break;
                        
                        case 'focus':
                            $('#route input[type=text]').not($el).animate({ width:50, color: '#666' } , { duration: 400, easing: equation, queue: false, complete: function(){} });
                            $el.animate({ width:200, color: '#333' }, { duration: 400 , easing: equation, queue: false, complete: function(){} });
                            //$title.animate({  }, { duration: 200 , easing: 'easeOutBack', queue: false, complete: function(){}});
                            $title.animate( { marginTop: 10, opacity: 0 } , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){
                                $title.css({ marginTop: -10, opacity: 0 });
                                $title.animate( { marginTop: 0, opacity: 1 } , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){}});
                            }});
                        break;
                        
                        
                        case 'blur':
                            $('#route input[type=text]').animate({ width:125, color: '#333' } , { duration: 400, easing: equation, queue: false, complete: function(){} });
                            //$title.animate({ color: '#9BDC49' , textShadow: '0 0 2px #9BDC49' }, { duration: 200 , easing: 'easeOutBack', queue: false, complete: function(){}});
                        break;
                    }
                    
                }
            },
            
            howto: function(e)
            {
                var $el     = $(e.currentTarget);
                var type    = e.type;
            
                //$el.css({ borderColor: '#d7fb9f' });
                //$('#how-to-use').hide();
                
                switch( type )
                {
                    case 'mouseenter':
                        $el.animate( { borderColor: '#d7fb9f' } , { duration: 200, easing: 'easeInOutQuad', queue: false, complete: function(){} });
                    break;

                    case 'mouseleave':
                        $el.animate( { borderColor: '#b6e470' } , { duration: 200, easing: 'easeInOutQuad', queue: false, complete: function(){} });
                    break;
                    
                    case 'click':
                        ui.map.overlay.large.open(e);
                        return false;
                    break;
                }
            },

            newtip: function(e)
            {
                
                var $el = $(e.currentTarget);
                var type = e.type;

                switch(type) {
                    case 'click':
                        track('/theride/home/dica');
                        ui.map.overlay.large.open(e);
                        // code
                        break;
                    
                    default:
                        // code
                }
                
                return false;
            }
            
        },
        
        sidebar: 
        {
            _defaults: {
                holder: '#sidebar',
                easingOut: 'easeOutBack',
                easingIn: 'easeInBack', 
                easing: 'easeOutExpo',
                duration: 800
            },
            
            show: function()
            {
                $(ui.map.sidebar._defaults.holder).css({display: 'block'}).animate({ right: -291 }, { duration: ui.map.sidebar._defaults.duration, easing: ui.map.sidebar._defaults.easing });
                return false;
            },
            
            hide: function()
            {
                $(ui.map.sidebar._defaults.holder).animate({ right: -340 }, { duration: ui.map.sidebar._defaults.duration, easing: ui.map.sidebar._defaults.easing, complete: function(){
                    $(this).css({display: 'none'})
                } });
                return false;
            },
            
            open: function(obj)
            {
                var sectionToOpen = obj || '#place-details';
                
                $(ui.map.sidebar._defaults.holder).css({display: 'block'}).animate({ right: 0 }, { duration: ui.map.sidebar._defaults.duration, easing: ui.map.sidebar._defaults.easing, complete: function(){
                    $('.d3-tooltip .text:contains("Sim"), .d3-tooltip .text:contains("Não")').parent().remove();
                    $('#voting label').d3_tooltip({ offset: [-18,-4], direction: 'top', width: '30px' });
                } });
                
                $('.tabs a').removeClass('active');
                $('#sidebar .tabs p a').css({backgroundColor: '#999', opacity: .4});
                
                switch(sectionToOpen)
                {
                    case '#place-details':
                        $('#sidebar .tabs p a#bt-details').css({display: 'block', backgroundColor: '#8dc147', opacity: 1});
                        //return;

                        $('#place-details .holder dt').removeClass('active');
                        var animParams = {'height': 0, 'paddingTop': 1, 'paddingBottom': 1, 'opacity': 0};
                        if(jQuery.browser.msie)
                            animParams = {'height': 0, 'paddingTop': 1, 'paddingBottom': 1};

                        $('#place-details .holder dd').css(animParams);

                        
                        //return;
                        $('#place-details .holder dt').unbind('click');
                        $('#place-details .holder dt').bind('click',function(){

                            if(!$(this).hasClass('active')){   

                                /* 
                                 * IE8 Crash animating with opacity. Fix this...
                                 */
                                var animParams = {'height': 0, 'paddingTop': 1, 'paddingBottom': 1, 'opacity': 0};
                                if(jQuery.browser.msie)
                                    animParams = {'height': 0, 'paddingTop': 1, 'paddingBottom': 1};

                                $('#place-details .holder dd').stop().animate(animParams,600, 'easeOutExpo');
                                var dd = $(this).next();

                                animParams = {'height': 100, 'opacity': 1, 'paddingTop': 3, 'paddingBottom': 3}; 
                                if(jQuery.browser.msie)
                                    animParams = {'height': 100, 'paddingTop': 3, 'paddingBottom': 3}; 
                                    
                                $(dd).stop().animate( animParams ,600, 'easeOutExpo');
                            }

                            $('#place-details .holder dt').removeClass('active');
                            $(this).addClass('active');
                        });
                        $('#place-details .holder dt:first').trigger('click');

                    break;
                    
                    case '#player':
                        $('#sidebar .tabs p a#bt-player').css({display: 'block', backgroundColor: '#8dc147', opacity: 1});
                    break;
                }
                
                /*
                 * Msie always crash with opacity animation...
                 */
                if(jQuery.browser.msie){
                
                    //$(ui.map.sidebar._defaults.holder).children().filter('section').css({display:'none'});
                    switch(sectionToOpen){
                        case '#place-details':
                            $('#player').css({'display':'none'});
                            break;
                        case '#player':
                            $('#place-details').css({'display':'none'});
                            break;
                    }
                    $(sectionToOpen).css({display:'block'});

                }else {
                
                    $(ui.map.sidebar._defaults.holder).children().filter('section').stop().animate({opacity: 0},{duration: 300, complete: function(){
                        $(this).css({display:'none'});
                    }});
                    $(sectionToOpen).stop().css({display:'block'}).animate({opacity: 1},300);

                }
                
                return false;
            },
            
            close: function()
            {
                $(ui.map.sidebar._defaults.holder).animate({ right: -291 }, { duration: ui.map.sidebar._defaults.duration, easing: ui.map.sidebar._defaults.easing });
                return false;
            }
        },

        error_overlay:
        {
            wink: function(t){

                $('#error_overlay').css({'display': 'block', 'opacity': 0, 'marginTop': -60}).animate({
                    'marginTop': -6,
                    'opacity': 1.0
                }, {'duration': 700, 'easing': 'easeOutBack', 'queue': false, complete: function(){
                        window.setTimeout( function(){
                            $('#error_overlay').animate({
                                'marginTop': -70,
                                'opacity': 0.0
                            }, {'duration': 700, 'easing': 'easeInBack', 'queue': false });
                        }, t);
                    }
                });
            }       
        
        },
        
        overlay:
        {
            large:
            {
                open: function(e)
                {
                    
                    var $el             = $(e.currentTarget);
                    var $overlay        = $('.overlay');
                    var overlayChild    = $($el.data('objToAppend'));
                    var childId         = $(overlayChild).attr('id');
                    
                    $($overlay).children().css({display: 'none', top: -40, opacity: 0});
                    
                    
                    $overlay
                    .css({
                        width: 200, 
                        height: 200,
                        left: '50%',
                        top: '50%',
                        marginLeft: -100,
                        marginTop: -100,
                        MozBorderRadiusTopleft: 100, 
                        MozBorderRadiusTopright: 100, 
                        MozBorderRadiusBottomleft: 100, 
                        MozBorderRadiusBottomright: 100, 
                        WebkitBorderTopLeftRadius: 100, 
                        WebkitBorderTopRightRadius: 100, 
                        WebkitBorderBottomLeftRadius: 100, 
                        WebkitBorderBottomRightRadius: 100,
                        opacity: 0,
                        display: 'block'
                    })
                    .animate(removeNonIEProps({ 
                        width: 906, 
                        height: 427,
                        left: 0,
                        top: 0,
                        marginLeft: 0,
                        marginTop: 0,
                        MozBorderRadiusTopleft: 6, 
                        MozBorderRadiusTopright: 6, 
                        MozBorderRadiusBottomleft: 6, 
                        MozBorderRadiusBottomright: 6, 
                        WebkitBorderTopLeftRadius: 6, 
                        WebkitBorderTopRightRadius: 6, 
                        WebkitBorderBottomLeftRadius: 6, 
                        WebkitBorderBottomRightRadius: 6,
                        opacity: 1
                    }),{duration: 600, easing: 'easeInOutQuad', queue: false, complete: function(){$(this).css({'filter':'none'});}});


                    $($overlay).append('<p id="overlay_close" class="close">fechar</p>');
                    $('.close').css({display: '', marginRight: -50}).fadeTo(0,0);

                    setTimeout(function() {
                        switch(childId)
                        {
                            case 'choose-city':
                                var labels = $(overlayChild).find('.maps label');
                                $("#gmaps-holder").css({opacity:0});
                                $(labels).css({opacity: 0, marginTop: -50 });
                                $('#choose-city .hgroup').css({ opacity: 0, marginTop: -50 });
                                $.each(labels, function(i){
                                    setTimeout(function() {
                                        $(labels[i]).animate({ opacity: 1, marginTop: 0 },{queue: false, duration: 600, easing: 'easeInOutQuad', complete: function(){$(this).css({'filter':'none'});} });
                                    }, i*120);
                                });
                                $('#choose-city .hgroup').css({display: 'block'}).animate({ opacity: 1, marginTop: 0 },{queue: false, duration: 1400, easing: 'easeInOutQuad', complete: function(){} });
                                $(overlayChild).css({display: 'block'}).animate({ opacity: 1, top: 0 },{queue: false, duration: 1200, easing: 'easeInOutQuad', complete: function(){$('#choose-city label').css({'filter':'none'});} });

                                // Disable header route fields
                                $('#map > header #route').css({'opacity': .4});
                                
                                $(labels).bind('click',function(){
                                    track('/theride/home/mapa/{city}/clicou'.substitute({'city': $('input',this).attr('value')}));

                                    $("#gmaps-holder").css({opacity:1});
                                    $(labels).removeAttr('checked');
                                    $(labels).removeClass('active');
                                    $('input',this).attr('checked','checked');
                                    $(this).addClass('active');

                                    $('#map > header #route').css({'opacity': 1.0});
                                    $("#gmaps-holder").css({opacity:1});
                                });
                                
                                $(labels).hover(function(){
                                    $('#choose-city .maps label').not(this).not('.active').stop().fadeTo(600,.4);
                                },function(){
                                    $('#choose-city .maps label').not(this).not('.active').stop().fadeTo(600,1);
                                });
                                
                                ui.map.overlay.large.appointCity();
                            break;
                            
                            case 'appoint-city':
                                var labels = $(overlayChild).find('.maps label');
                                $("#gmaps-holder").css({opacity:0});
                                $(labels).css({opacity: 0, marginTop: -50 });
                                $('#appoint-city hgroup').css({ opacity: 0, marginTop: -50 });
                                $.each(labels, function(i){
                                    setTimeout(function() {
                                        $(labels[i]).animate({ opacity: 1, marginTop: 0 },{queue: false, duration: 600, easing: 'easeInOutQuad', complete: function(){} });
                                    }, i*120);
                                });
                                $('#appoint-city hgroup').css({display: 'block'}).animate({ opacity: 1, marginTop: 0 },{queue: false, duration: 1400, easing: 'easeInOutQuad', complete: function(){} });
                                $(overlayChild).css({display: 'block'}).animate({ opacity: 1, top: 0 },{queue: false, duration: 1200, easing: 'easeInOutQuad', complete: function(){$(overlayChild).css({'filter':'none'});} });
                                
                                $(labels).bind('click',function(){
                                    track('/theride/home/escolhacidade/{city}/clicou'.substitute({'city': $('strong',this).text().split(' - ')[1]}));

                                    $("#gmaps-holder").css({opacity:1});

                                    $(labels).removeAttr('checked');
                                    $(labels).removeClass('active');

                                    $('input',this).attr('checked','checked');
                                    $(this).addClass('active');
                                    

                                    $("#appoint-other").val( $('strong',this).text() );
                                });

                                setTimeout(function() {
                                    $(labels).bind('mouseenter', function(){
                                        $('#appoint-city .maps label').not(this).not('.active').stop().fadeTo(600,.4);
                                    });
                                    $(labels).bind('mouseleave', function(){
                                        $('#appoint-city .maps label').not(this).not('.active').stop().fadeTo(600,1);
                                    });

                                    $('#appoint-other').bind('focus', function(){
                                        track('/theride/home/escolhacidade/cidadeoutra/clicou');
                                    });
                                }, 1500);
                                ui.map.overlay.large.appointCity();                                                     
                            break;
                            
                            case 'how-to-use':
                                $('#how-to-use hgroup').css({ opacity: 0, marginTop: -20 });
                                $('#how-to-use ol').css({ opacity: 0, marginLeft: -20 });
                                $('#how-to-use hgroup').css({display: 'block'}).animate({ opacity: 1, marginTop: 0 },{queue: false, duration: 800, easing: 'easeInOutQuad', complete: function(){} });
                                $('#how-to-use ol').css({display: 'block'}).animate({ opacity: 1, marginLeft: 0 },{queue: false, duration: 800, easing: 'easeInOutQuad', complete: function(){} });
                                $(overlayChild).css({display: 'block'}).animate({ opacity: 1, top: 0 },{queue: false, duration: 200, easing: 'easeInOutQuad', complete: function(){} });
                            break;

                            case 'new-hint':
                                $('#new-hint').css({ display: 'block', opacity: 0 }).animate({ opacity: 1, top: 0},{queue: false, duration: 800, easing: 'easeInOutQuad'});
                                break;
                            
                        }
                        setTimeout(function() {
                            $('.close').animate({opacity: 1, marginRight: 0}, { duration: 1000, queue: false });
                        }, 500);
                        
                        
                    }, 380);
                    
                    
                    
                    return false;
                },
                
                close: function(e)
                {
                    var coords = $getDeepUri();
                    var city = false;
                    if(coords){
                        city = coords[3];
                    }
                    var $el         = $(e.currentTarget);
                    var $overlay    = $('.overlay');

                    var hideErrorTips = function(el){
                        var tip = $E(el).retrieve("tip") || false;
                        if(tip)
                            tip.hide(); 
                    }
                    hideErrorTips( '#appoint-confirm-name' );
                    hideErrorTips( '#appoint-confirm-email' );
                    
                    $overlay
                    .animate({ 
                        opacity: 0
                    },{duration: 400, easing: 'easeInOutQuad', queue: false, complete: function(){ 
                        $overlay.children().css({display: 'none'});
                        $(this).css({display: 'none'});
                        if(!city){
                            $("#gmaps-holder").css({opacity:0});

                            $('#city-helper').remove();
                            $('<span id="city-helper"></span>').hide().appendTo('body');
                            $('#city-helper').data('objToAppend','#choose-city').bind( 'click' , ui.map.overlay.large.open );
                            $('#city-helper').trigger('click');

                            // Hide close button for choose-city page
                            setTimeout(function() {
                                $('#overlay_close').css('display','none');
                            }, 500);
                            

                        }else{
                            $("#gmaps-holder").css({opacity:1});
                        }

                        $('#appoint-city .maps label').unbind('mouseenter mouseleave');
                    }});
                    
                    return false;
                    
                },
                
                appointCity: function()
                {
                    var inputs = $('.appoint-confirm input[type=text]');
                    
                    $(inputs).eq(0).val('Nome');
                    $(inputs).eq(1).val('E-mail');
                    
                    if(!$(inputs).eq(0).data('firstTime')){
                        
                        //$(inputs).unbind('focus blur');
                        
                        $(inputs).eq(0).data('firstTime','yes');
                        
                        $.each(inputs, function(i){
                            
                            $(inputs[i]).data('value',$(inputs[i]).val());
                            
                            $(inputs[i]).bind('focus', function(){
                                var myValue     = $(this).val().trim();
                                var myData      = $(this).data('value');
                                if(myValue == myData) {
                                    $(this).val('');
                                }
                            });

                            $(inputs[i]).bind('blur', function(){
                                var myValue     = $(this).val().trim();
                                var myData      = $(this).data('value');
                                if(myValue == myData || myValue == '') {
                                    $(this).val(myData);
                                }
                            });
                            
                        });
                        
                    }
                    
                }
            },
            small:
            {
                
            }
        },
        
        holder: function(e)
        {
            var $el     = $(e.currentTarget);
            var type    = e.type;
            
            switch( type )
            {
                case 'mouseenter':
                    $el.stop().animate( removeNonIEProps({ MozBorderRadius: 20, borderColor: '#777', WebkitBorderTopLeftRadius: 20, WebkitBorderTopRightRadius: 20, WebkitBorderBottomLeftRadius: 20, WebkitBorderBottomRightRadius: 20 }) , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){}});
                break; 
                
                case 'mouseleave':
                    $el.stop().animate( removeNonIEProps({ MozBorderRadius: 8, borderColor: '#333', WebkitBorderTopLeftRadius: 8, WebkitBorderTopRightRadius: 8, WebkitBorderBottomLeftRadius: 8, WebkitBorderBottomRightRadius: 8 }) , { duration: 400, easing: 'easeOutBack', queue: false, complete: function(){}});
                break;
            }
        },
        
        formsTitle: function(e)
        {
            var $el     = $(e.currentTarget).find('h2 > span');
            var type    = e.type;
            
            switch( type )
            {
                case 'mouseenter':
                    $el.animate( { marginLeft: 50, opacity: 0 } , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){
                        $el.css({ marginLeft: -100, opacity: 1 });
                        $el.animate( { marginLeft: 0, opacity: 1 } , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){}});
                    }});
                break;
                
                case 'mouseleave':
                    $el.stop().animate( removeNonIEProps({ MozBorderRadius: 8, borderColor: '#333', WebkitBorderTopLeftRadius: 8, WebkitBorderTopRightRadius: 8, WebkitBorderBottomLeftRadius: 8, WebkitBorderBottomRightRadius: 8 }) , { duration: 400, easing: 'easeOutBack', queue: false, complete: function(){}});
                break;
            }
        }
        
    },
    
    
    commonFx: function(e)
    {
        var $el     = $(e.currentTarget);
        var elId    = $el.attr('id');
        var $elLabel= $('label[for='+elId+']').length ? $('label[for='+elId+']') : $el.siblings('label:first');
        var type    = e.type;
        var elType  = $el.attr('type') ? $el.attr('type') : e.currentTarget.nodeName.toLowerCase();
        
    /*  if(!$elLabel.length){
            $elLabel = $('label[title='+elId+']');
        }*/
        
        switch(type)
        {
            case 'mouseenter':
            case 'focus':
                // bt-1 && input[type=text]
                if (elType == 'text' && $el.hasClass('.bt-1'))
                {

                    $el.animate(
                    removeNonIEProps({ 
                        backgroundColor: '#fff',
                        MozBoxShadow: '0px 0px 3px 1px #9BDC49, 0px 0px 3px 2px #ddd inset, 0px 5px 3px 1px #eee inset'
                    }), { duration: 200 , easing: 'linear', queue: false, complete: function(){
                        $el.css(removeNonIEProps({
                            'background-color': '#fff',
                            '-moz-box-shadow': '0px 0px 3px 1px #9BDC49, 0px 0px 3px 2px #ddd inset, 0px 5px 3px 1px #eee inset'
                        }));
                    } });
                    
                    $elLabel.animate(removeNonIEProps({
                        color: '#9BDC49',
                        textShadow: '0 0 2px #9BDC49'
                    }), { duration: 200 , easing: 'linear', queue: false, complete: function(){}})

                }
                
                // bt-1 && submit || a || button
                if ((elType == 'submit' || elType == 'button' || elType == 'a') && $el.hasClass('.bt-1'))
                {
                    $el.stop().animate(
                    removeNonIEProps({ 
                        backgroundColor: '#9bdc49',
                        color: '#fff',
                        //borderColor: '#b6e470',
                        MozBoxShadow: '0px 0px 3px 1px #6da430, 0px 2px 2px 3px #b6e470 inset, 0px -4px 2px 3px #6da430 inset',
                        textShadow: '0 0 3px #000'
                    }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });
                    
                    
                    
                }
            break;
            
            case 'mouseleave':
            case 'blur':
            
                // bt-1 && input[type=text]
                if (elType == 'text' && $el.hasClass('.bt-1'))
                {
                    if((type=='mouseleave' && currentFocus != e.currentTarget) || type=='blur') {

                        $el.animate(
                        removeNonIEProps({ 
                            backgroundColor: '#e2e2e2',
                            MozBoxShadow: '0px 0px 3px 1px #333, 0px 0px 3px 2px #aaa inset, 0px 5px 3px 1px #bbb inset'
                        }), { duration: 200 , easing: 'linear', queue: false    , complete: function(){
                            $(this).css(removeNonIEProps({
                                'background-color': '#e2e2e2',
                                MozBoxShadow: '0px 0px 3px 1px #333, 0px 0px 3px 2px #aaa inset, 0px 5px 3px 1px #bbb inset'
                            }));
                        } });
                        
                        $elLabel.animate(removeNonIEProps({
                            color: '#ccc',
                            textShadow: '0 0 2px #aaa'
                        }), { duration: 200 , easing: 'linear', queue: false, complete: function(){}});
                    }
                    
                    
                }
                
                // bt-1 && submit || a || button
                if ((elType == 'submit' || elType == 'button' || elType == 'a') && $el.hasClass('.bt-1'))
                {
                    $el.stop().animate(
                    removeNonIEProps({ 
                        backgroundColor: '#e2e2e2',
                        color: '#000',
                        //borderColor: '#222',
                        MozBoxShadow: '0 0 3px 1px #000, 0 0 3px 2px #aaa inset, 0 5px 3px 1px #bbb inset',
                        textShadow: '0 0 0 #fff'
                    }), { duration: 200 , easing: 'linear', queue: false, complete: function(){} });
                }
            break;
        }
    },
    
    
    commonHover: function(e)
    {
        var $el     = $(e.currentTarget);
        var type    = e.type;
        
        switch( type )
        {
            case 'mouseenter':
                $el.stop().animate( { color: '#fff', backgroundPosition: '-165px -9px', paddingLeft: 18 } , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){}});
            break;
            
            case 'mouseleave':
                $el.stop().animate( { color: '#ddd', backgroundPosition: '-200px -9px', paddingLeft: 7  } , { duration: 200, easing: 'easeOutQuad', queue: false, complete: function(){}});
            break;
        }
    },
    
    hintHover: function(e)
    {
        var type    = e.type;
        
        switch( type )
        {
            case 'mouseenter':
                $("#hint-button").stop().animate( { opacity: 0 } , { duration: 200, queue: false} );
            break;
            
            case 'mouseleave':
                $("#hint-button").stop().animate( { opacity: 1 } , { duration: 200, queue: false} );
            break;
        }
    },
    
    bindEvents: function()
    {
                
        // current focus
        $('*').bind('focus',function(e){ currentFocus = e.currentTarget; });
        $('*').bind('blur',function(e){ currentFocus = 'nothing'; });
        
        // append span inside element
        // var alinksBt1 = $('a.bt-1, #howto');
        //      $.each(alinksBt1,function(obj){
        //          $(alinksBt1[obj]).html('<span>' + $(alinksBt1[obj]).text() + '</span>');
        //      });
        
        // common
        $('.bt-1').bind( 'mouseenter mouseleave focus blur' , ui.commonFx );
        $('.bt-2').bind( 'mouseenter mouseleave focus blur' , ui.commonFx );
        
        //map holder
        //$('#map-holder').bind('mouseenter mouseleave', ui.map.holder );
        
        // Suggest_city
        $('#suggest_city').bind('click',function(){
            track("/theride/home/escolhacidade_1/outra_cidade/clicou");
        });
        
        //map howto button
        $('#howto').data('objToAppend','#how-to-use').bind( 'mouseenter mouseleave focus blur click' , ui.map.header.howto );

        //send you tip 
        $('#newhint').data('objToAppend','#new-hint').bind( 'mouseenter mouseleave focus blur click' , ui.map.header.newtip );
        
        $('#route input[type=text]').bind( 'mouseenter mouseleave focus blur' , ui.map.header.localization.inputText );

        $('#localization input ~ abbr').bind( 'mouseenter mouseleave click' , ui.map.header.localization.changeState );
        
        // tooltips
        $('abbr:first').d3_tooltip({ offset: [-15,-17], direction: 'top' });
        $('abbr:last').d3_tooltip({ offset: [-15,-28], direction: 'top' });
        $('#nav,#howto').d3_tooltip({ offset: [-15,-35], direction: 'top' });
        

        
        //$('#whereami').d3_tooltip({ offset: [-15,-50], direction: 'top', text: 'Descubra onde estou' });
        
        //$('*[title="Arraste para reposicionar"]').d3_tooltip({ offset: [-15,-28], direction: 'top', text: 'Yes baby' });
        /*$('.gmnoprint').live('mouseover',function(){
            trace('-----');
        });*/
	    
        // Ad hovers
        $('#ad-1').hover( function(){
            $('#ad-caption', this).animate({'opacity': 1.0}, 150, 'easeOutQuad');
        }, function(){
            $('#ad-caption', this).animate({'opacity': 0.5}, 150, 'easeOutQuad');
        });

        $('#ad-1').bind('click',function(){
            track('/theride/home/destaque/clicou');
        });

        // ad-2 click opens appoint-city
        $('#ad-2').bind('click', function(e){
            track('/theride/home/escolhacidade_2/clicou');


            // Scroll page to TOP
            $('html,body').animate( {scrollTop: 0}, {duration: 500, easing: 'easeOutQuad', queue: false} );

            // Open appoint-city
            $('#ad-2').data('objToAppend','#appoint-city');
            ui.map.overlay.large.open( {'currentTarget': '#ad-2'} );

            return false;       
        });
        
        // localization link
        $('#localization a, a#route-link').bind( 'mouseenter mouseleave' , ui.commonHover );
        
        // overlay
        $('.overlay').hide().fadeTo(0,0);
        $('#localization a').data('objToAppend','#appoint-city').bind( 'click' , ui.map.overlay.large.open );
        $('.overlay .close, .overlay .cancel-button').live( 'click' , ui.map.overlay.large.close );
        
        // call to player
        $('#player-musics .button-download').bind('click', function(){
            ui.map.sidebar.open('#player');
            return false;
        });
        
        $('.tabs #bt-player').bind('click', function(){
            var state = ($('#localization input:checked').val() || "SP");
            track('/theride/home/cidade{city}/musica/tip/clicou'.substitute({'city': state}));

            ui.map.sidebar.open('#player');
            return false;
        });
        
        $('.tabs #bt-details').bind('click', function(){
            ui.map.sidebar.open('#place-details');
            return false;
        });
                
        $('#sidebar .close').bind('click',function(){
            ui.map.sidebar.close();
        });
        
        // appoint city
        $('#appoint-city > #return-message a').live( 'click' , ui.map.overlay.large.close );
        $('#appoint-city > #return-message').fadeTo(0,0);       
        
        $('#appoint-city form').bind('submit', function(e){
            e.preventDefault;
        });

        $E("#appoint-confirm-name").store("tip", false);
        $E("#appoint-confirm-email").store("tip", false);
        $('#appoint-city input[type=submit]').bind('click',function(){

            var field_errorset  = function(element, error){
                if(error) {

                    var tip = $E(element).retrieve("tip") || false;
                    if(!tip){

                        if(element.match(/name/)){
                            tip = $(element).d3_tooltip({ offset: [-15,-50], direction: 'top', text: "Opa, você esqueceu de seu nome!", shouldHover: false , 'klass': 'd3-tooltip-error'});
                            trace("Creating tip: %s", element);

                        }else if(element.match(/email/))
                            tip = $(element).d3_tooltip({ offset: [-15,-25], direction: 'top', text: "Precisamos de seu email também.", shouldHover: false , 'klass':'d3-tooltip-error'});

                        tip = tip[0];
                    } 

                    tip.show();
                    $E(element).store("tip", tip);

                } else {
                    var tip = $E(element).retrieve("tip") || false;
                    if(tip)
                        tip.hide(); 

                    $E(element).store("tip", false);
                }
            };

            var name  = $('#appoint-confirm-name').val();
            var city  = $('#appoint-other').val();
            var email = $('#appoint-confirm-email').val();

            var isValid = {
                            'name': name.trim() != '' && name.trim() != 'Nome', 
                            'email': email.test(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)
                          };

            field_errorset( '#appoint-confirm-name', !isValid['name']);
            if(isValid['name'])
                field_errorset( '#appoint-confirm-email', !isValid['email']);
            else
                field_errorset( '#appoint-confirm-email', false);

            if( isValid['name'] && isValid['email']){

                track('/theride/home/mapa/{city}/confirmou'.substitute({'city': $('#appoint-other').attr('value')}));

                $.post('/appoint/save', $('#appoint-city form').serialize(),
                      function(responseData){
                      trace('saved');
                });

                $('#appoint-city > .header, #appoint-city > form').animate({opacity: 0, marginTop: -800}, 400, 'easeOutQuad', function() {$(this).hide();} );
                $('#appoint-city > #return-message').animate({opacity: 1, marginTop: 180}, 400, 'easeOutQuad', function() {} );

                $('#appoint-city hgroup').animate({ opacity: 0, marginTop: -50 },{queue: false, duration: 400, easing: 'easeInOutQuad', complete: function(){
                    $(this).css({marginLeft: -500});
                }});
            } 
            return false;
        });
        
        /*
         * Footer buttons
         */
        $('#termos-link').bind('click', ui.termosDeUso.toggle);     
        $('#termos #fechar_contracts').bind('click', ui.termosDeUso.toggle);        
        $('#policia-link').bind('click', ui.politicaPrivacidade.toggle);
        $('#policia #fechar_contracts').bind('click', ui.politicaPrivacidade.toggle);       
        
        // gambiarra
        // $('#localization label[for=rj] abbr').trigger('click');
        // $('#localization label[for=rj] input').trigger('click');
        // $('#localization label[for=rj] abbr').trigger('click');
        // $('#localization label[for=rj] input').trigger('click');
        //$('#localization :checked ~ abbr').trigger('click');
	    
	    // Hint link
        $('#newhint').bind( 'mouseenter mouseleave' , ui.hintHover );
    },

    /*
     * Controls footer PoliciaDePrivacidade and termosDeUso
     */
    termosDeUso: {
        isOpen: false,
        hasJScroll: false,
        'open': function(e){
            if(ui.politicaPrivacidade.isOpen)
                ui.politicaPrivacidade.close();
                
            $('#termos').css({'opacity': 0,'display': 'block'});
            $('#termos').stop().animate({ 
                opacity: 1.0
            }, { duration: 200 , easing: 'linear', queue: false, complete: function(){
                    if(! ui.termosDeUso.hasJScroll){
                        $('#termos-holder').jScrollPane();
                        ui.termosDeUso.hasJScroll = true;
                    }
            } }); 
            
            ui.termosDeUso.isOpen = true;
            return false;
        },
        'close': function(e){
            $('#termos').stop().animate({ 
                opacity: 0.0
            }, { duration: 200 , easing: 'linear', queue: false, complete: function(){ 
                    $('#termos').css({'display':'none'});
            } });

            ui.termosDeUso.isOpen = false;          
            return false;
        },
        
        'toggle': function(e){
            if(ui.termosDeUso.isOpen)
                ui.termosDeUso.close();
            else
                ui.termosDeUso.open();
                
            return false;
        }
    },

    politicaPrivacidade: {
        isOpen: false,
        hasJScroll: false,
        'open': function(e){
            if(ui.termosDeUso.isOpen)
                ui.termosDeUso.close()
                            
            $('#policia').css({'opacity': 0,'display': 'block'});
            $('#policia').stop().animate({ 
                opacity: 1.0
            }, { duration: 200 , easing: 'linear', queue: false, complete: function(){
                if(! ui.politicaPrivacidade.hasJScroll){
                    $('#policia-holder').jScrollPane();
                    ui.politicaPrivacidade.hasJScroll = true;
                }
            } });

            ui.politicaPrivacidade.isOpen = true;
        },
        'close': function(e){
            $('#policia').stop().animate({ 
                opacity: 0.0
            }, { duration: 200 , easing: 'linear', queue: false, complete: function(){ 
                $('#policia').css({'display':'none'});
            }});
        
            ui.politicaPrivacidade.isOpen = false;          
        },
        'toggle': function(e){
            if(ui.politicaPrivacidade.isOpen)
                ui.politicaPrivacidade.close();
            else
                ui.politicaPrivacidade.open();
            
            return false;
        }       
    }
}

function trace() {
    for (var i = 0, args=[]; i < arguments.length; i++) args[i] = arguments[i]; 
    if (window.console && console.log) console.log(args);
}

function refreshMapTooltips(){
    var dragText = 'Arraste para reposicionar';
    $('.d3-tooltip .text:contains("'+dragText+'")').parent().remove();
    $('*[title="Arraste para reposicionar"]').d3_tooltip({ offset: [-15,-55], direction: 'top', text: dragText });
}

$(document).ready(function(){
    ui.bindEvents();
    setTimeout(function(){
        $("#hint-button").stop().fadeTo(400,1);
        $("#hint-button-over").stop().fadeTo(400,1);
    },2000);
    
    // SOUND
    soundManager.url       = '/media/swf'; 
    soundManager.debugMode = false;      
    soundManager.consoleOnly = false;
    player.init();

});
