var EquipaDAfrica = {
    filtrar : function(range){
        var that = this;
        var path = window.location.pathname, pais = null;
        path = path.substring(1, path.length-1).split('/');
        $.ajax({
            url: '/onde-estivemos/',
            type: 'POST',
            data: {
                'pais': path.length == 2 ? path[1] : '',
                'anos': '['+range[0]+','+range[1]+']'
            },
            success: function(data, status){
                $('#locais').replaceWith(data);
                //$.each(data, that.renderLocal);
            }
        });
    },
    
    renderLocal : function(local){
        console.log(local);
    },
    
    showLocalMapa : function(location){
        var el = $('#local-mapa').show();
        if (!this.map){
            var pos = new google.maps.LatLng(location.lat, location.lng);
            this.map = new google.maps.Map(el.get(0), {
                streetViewControl: false,
                zoom: 8,
                center: pos,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            var marker = new google.maps.Marker({
                position: pos,
                map: this.map,
                title: "!!!",
                icon: MEDIA_URL + 'static/img/map-marker.png',
                flat: true
            });
        }
    }
};

$(function(){
    /*if (screen.width <= 1366){
        $('body').removeClass('bg-max').addClass('bg-min')
    }else if (screen.width <= 1680){
        $('body').removeClass('bg-max').addClass('bg-med')
    }
    var bgsrc = $('#container').css('background-image');
        bg = $('<img id="bg-image" />').appendTo('#container');
    bg.attr('src', bgsrc.replace('url("', '').replace('")', ''));
    $("#container").backgroundScale({
        imageSelector: "#bg-image",
        centerAlign: true,
        containerPadding: 0
    });*/
    
    EquipaDAfrica.Nav.init('#nav');
    
    $('.column.left ul a').not('.clear-pais').hover(function(){
        $(this).stop().animate({
            'padding-left': '34px'
        }, 'fast');
    }, function(){
        $(this).stop().animate({
            'padding-left': '28px'
        }, 'fast');
    });
    
    // Home - Destaques
    $('#destaques-list').carousel({
        pagination: true,
        paginationPosition: 'outside',
        effect: 'fade',
        loop: true,
        autoSlide: $('#destaques-list li').length > 1 ? true : false,
        autoSlideInterval: 5000
    }).find('li').height(244);
    
    $('#eventos h3 a').fancybox({
        overlayColor: '#000',
        autoScale: true,
        padding: 0,
        titleFormat : function(title, all, index, opts){
            var id = $(all[index]).attr('id').replace('btn', 'title');
            return $('#'+id).html();
        }
    });

    $('.novidade h3 a').fancybox({
        overlayColor: '#000',
        titleShow: false
    });
    
    if ($('#newsletter').length){
        $('#newsletter form').bind('submit', function(){
            var form = $(this).addClass('loading');
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: {'email': $('#newsletter-email').val()},
                success: function(response){
                    $('#newsletter-mensagem p').html(response);
                    form.removeClass('loading');
                }
            });

            return false;
        });
    }
    
    // Onde Estivemos
    $('a.clear-pais').bind('click', function(){
        window.location = '/onde-estivemos/';
        
        return false;
    });
    $('#years-range').slider({
        range: true,
        min: 1998,
        max: 2010,
        values: [1998, 2010],
        slide: function(event, ui){
            $('#year-first').html(ui.values[0]);
            $('#year-last').html(ui.values[1]);
        },
        start : function(){
            $('#locais').css('opacity', .3);
            $('h2').addClass('loading');
        },
        stop: function(event, ui){
            window.location.hash = '#/anos/' + ui.values.join('-') + '/';
            EquipaDAfrica.filtrar(ui.values);
            $('h2').removeClass('loading');
        }
    });
    if ($('#years-range').length){
        $('.column.main h2').append('<span class="spinner"></span>');
        setTimeout(function(){
            $('#year-first').appendTo('.ui-slider-handle:eq(0)').show();
            $('#year-last').appendTo('.ui-slider-handle:eq(1)').show();
        }, 300);
    }
    
    // O Que Fazemos
    if ($('#local, #projecto').length){
        var loader = $(new Image()),
            $foto = $('#local-foto img, #projecto-foto img');
        $(loader).bind('load', function(){
            $foto.attr('src', $(this).attr('src')).fadeIn();
        });
        if ($('#local-fotos li, #projecto-fotos li').length > 6){
            $('#local-fotos, #projecto-fotos').carousel({
                dispItems: 5
            });
        }
        $('#local-fotos li a, #projecto-fotos li a').bind('click', function(){
            var src = $(this).attr('href');
            $('#local-mapa').hide();
            $foto.fadeOut(function(){
                $(loader).attr('src', src);
            });
            return false;
        });
        
        // Mapa
        $('#mapa-btn').bind('click', function(){
            var parts = $(this).attr('href').replace('#', '').split('|'),
                location = {
                    lat: parseFloat(parts[0].replace(',', '.')),
                    lng: parseFloat(parts[1].replace(',', '.')),
                };
            $foto.fadeOut(function(){
                if (!google.maps){
                    google.load('maps','3.x', {
                        other_params: 'sensor=false',
                        callback: function(){
                            EquipaDAfrica.showLocalMapa(location);
                        }
                    });
                }else{
                    EquipaDAfrica.showLocalMapa(location);
                }
            });
            return false;
        });
    }
    
    //$('#categoria-fotos a').fancyZoom();
    $('#categoria-fotos a').fancybox({
        padding: 0
    });
    
    // Merchandising
    if ($('#produtos').length){
    	var COLOR_INDEX = {}, btns = [
    	    '<a class="color-nav-prev disabled" href="#" title="Cor anterior">Cor anterior</a>',
    	    '<a class="color-nav-next" href="#" title="Cor seguinte">Cor seguinte</a>'];
    	var loader = $(new Image()).bind('load', function(){
    		var img = $(this).data('target');
    		$(img).attr('src', $(this).attr('src')).fadeIn();
    	});
    	
    	/*function colorNav(el, id, index){
    		if ($(el).is('.color-nav-prev')){
    			if (COLOR_INDEX[id] == 0){
    				return false;
    			}
    			COLOR_INDEX[id]--;
    			$('.produto .color-nav-next').removeClass('disabled');
    			if (COLOR_INDEX[id] == 0){
    				$(this).addClass('disabled');
    			}
    		}else{
    			if (COLOR_INDEX[id] == (COLORS[id].length - 1)){
    				return false;
    			}
    			COLOR_INDEX[id]++;
    			$('.produto .color-nav-prev').removeClass('disabled');
    			if (COLOR_INDEX[id] == (COLORS[id].length - 1)){
    				$(el).addClass('disabled');
    			}
    		}
    	}*/
    	
    	$('.produto .color-nav-prev, .produto .color-nav-next').live('click', function(e){
    		var id = $(this).parents('.produto-wrap').attr('id').replace('produto-', '');
			//$(this).removeClass('disabled');
    		if ($(this).is('.color-nav-prev')){
    			if (COLOR_INDEX[id] == 0){
    				return false;
    			}
    			COLOR_INDEX[id]--;
    			$('.produto .color-nav-next').removeClass('disabled');
    			if (COLOR_INDEX[id] == 0){
    				$(this).addClass('disabled');
    			}
    		}else{
    			if (COLOR_INDEX[id] == (COLORS[id].length - 1)){
    				return false;
    			}
    			COLOR_INDEX[id]++;
    			$('.produto .color-nav-prev').removeClass('disabled');
    			if (COLOR_INDEX[id] == (COLORS[id].length - 1)){
    				$(this).addClass('disabled');
    			}
    		}
    		//console.log(COLORS[id]);
    		var src = COLORS[id][COLOR_INDEX[id]].image.list;
    		var label = $(this).parent().find('.color-info span').fadeOut('fast');
			$(this).parent().find('img').fadeOut(function(){
				label.html(COLORS[id][COLOR_INDEX[id]].name).fadeIn();
				loader.data('target', this).attr('src', src);
			});
    		return false;
    	});

    	$.each(COLORS, function(id, colors){
    		var produto = $('#produto-' + id + ' .produto');
    		if (colors.length > 0){
    			produto.append('<div class="color-info"><span>'+ colors[0].name +'</span></div>');
    		}
    		if (colors.length > 1){
    			produto.append(btns.join(''));
    			COLOR_INDEX[id] = 0;
    		}
    	});
    	
        $('.produto-wrap').hover(function(){
            $(this).find('h4').stop().animate({
                top: '143px'
            }, 'fast');
        }, function(){
            $(this).find('h4').stop().animate({
                top: '127px'
            }, 'fast');
        });
        
        $('.produto-wrap h4 a').fancybox({
            padding: 0
        });
    }
});

EquipaDAfrica.Nav = (function(){
    var that, ghost, interval;

    return {
        init : function(selector){
            that = this;

            this.el = $(selector);
            this.current = this.el.find('li.current a').get(0);

            this.el.bind('mouseleave', function(){
                if (ghost){
                    that.back.animate({'opacity': 0}, function(){
                        ghost = false;
                    });
                }
            });

            this.el.find('a').hover(function(){
                that.slideBack(this);
            }, function(){
                if (that.current){
                    that.slideBack(that.current);
                }
            }).click(function(){
                return that.select(this);
            });

            this.el.append('<li class="background"><div class="left">&nbsp;</div></li>');
            this.back = this.el.find("li.background").css('opacity', 0);
            if(this.current){
                this.setCurrent(this.current);
            }
        },

        slideBack : function(to){
            if(!this.current && !ghost){
                ghost = true;
                this.back.css({
                    'left': to.offsetLeft,
                    'width': to.offsetWidth
                }).stop(true).animate({
                    'opacity': 1
                });
            } else {
                this.back.stop(true).animate({
                    'left': to.offsetLeft,
                    'width': to.offsetWidth,
                    'opacity': 1
                }, 300, 'swing');
            }
        },

        setCurrent : function(el){
            this.back.css({
                'left': el.offsetLeft,
                'width': el.offsetWidth,
                'opacity': 1
            });
        },

        select : function(el){
            if(!this.current){
                this.setCurrent(el);
            }
            this.current = el;
        }
    }
})();

