/*
@author: Thomas Rambaud
@website: http://thomasrambaud.com
*/
var FBNFactory = (function($){
    
    var $win = $(window);
    
    ''.trim || (String.prototype.trim = function () {
        return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '');
    });
    
    $(document).ready(function(){
        FBNFactory.init();
    });
    
    return {
        init: function(){
            this.menu();
            this.fullHeights();
            this.burgerMenu();
            this.carousel();
            this.externalLinks();
            this.googleMaps();
        },
        
        menu: function(){
            var $menu = $('#menu-main');
            if($menu.length === 0) return;
            if($menu.find('.sub-menu:visible').length > 0){
                $menu.children().children().addClass('has-submenu');
            }
        },
        
        fullHeights: function(){
            var $fullHeights = $('.fullh');
            
            function resizeDivs(){
                $fullHeights.each(function(){
                    $(this).height($(this).parent().height() - 80);
                });
            }
            
            $win.on('resize', function(){
                if($(this).width() <= 1024){
                    $fullHeights.css('height', 'auto');
                }else{
                    resizeDivs();
                }
            }).trigger('resize');
        },
        
        externalLinks: function(){
            $.expr[':'].external = function(obj){
                return !obj.href.match(/^mailto\:/)
                       && (obj.hostname != location.hostname)
                       && !obj.href.match(/^javascript\:/)
                       && !obj.href.match(/^$/)
            };
            
            $('a:external').attr('target', '_blank');
        },
        
        googleMaps: function(){
            $('.googleMap').each(function(){
                FBNFactory.googleMap($(this));
            });
        },
        
        googleMap: function($obj){
            // generates google maps fort shortcodes
            FBNFactory.getLatLng($obj.data('address'), function(results, status){
                if(status == google.maps.GeocoderStatus.OK) {
                    var styles = [{"featureType":"water","elementType":"all","stylers":[{"hue":"#7fc8ed"},{"saturation":55},{"lightness":-6},{"visibility":"on"}]},{"featureType":"water","elementType":"labels","stylers":[{"hue":"#7fc8ed"},{"saturation":55},{"lightness":-6},{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"hue":"#83cead"},{"saturation":1},{"lightness":-15},{"visibility":"on"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"hue":"#f3f4f4"},{"saturation":-84},{"lightness":59},{"visibility":"on"}]},{"featureType":"landscape","elementType":"labels","stylers":[{"hue":"#ffffff"},{"saturation":-100},{"lightness":100},{"visibility":"off"}]},{"featureType":"road","elementType":"geometry","stylers":[{"hue":"#ffffff"},{"saturation":-100},{"lightness":100},{"visibility":"on"}]},{"featureType":"road","elementType":"labels","stylers":[{"hue":"#bbbbbb"},{"saturation":-100},{"lightness":26},{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"hue":"#ffcc00"},{"saturation":100},{"lightness":-35},{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"hue":"#ffcc00"},{"saturation":100},{"lightness":-22},{"visibility":"on"}]},{"featureType":"poi.school","elementType":"all","stylers":[{"hue":"#d7e4e4"},{"saturation":-60},{"lightness":23},{"visibility":"on"}]}],
                        mapTypeId = 'fben',
                        mapOptions = {
                            zoom: 11,
                            center: results[0].geometry.location,
                            mapTypeControl: false,
                            //draggable: false,
                            //scaleControl: false,
                            //scrollwheel: false,
                            //navigationControl: false,
                            streetViewControl: false,
                            //zoomControl: false,
                            mapTypeControlOptions: {
                              mapTypeIds: [google.maps.MapTypeId.ROADMAP, mapTypeId]
                            },
                            mapTypeId: mapTypeId
                        },
                        styledMapOptions = {
                            name: 'fben'
                        },
                        customMapType = new google.maps.StyledMapType(styles, styledMapOptions);

                        if($win.width() <= 640){
                            mapOptions.draggable = false;
                            mapOptions.zoom = 5;
                        }

                        var map = new google.maps.Map($obj.children()[0], mapOptions),
                            infoWindow = new google.maps.InfoWindow(),
                            marker = new google.maps.Marker({
                                position: results[0].geometry.location,
                                map: map,
                                title: $obj.data('name'),
                                icon: 'http://www.francebenevolat.org/sites/all/themes/fbn/img/gmap-marker.png'
                            });

                        map.mapTypes.set(mapTypeId, customMapType);
                    
                        infoWindow.setContent('<div class="fbn-iw">' + $obj.data('name') + '<br>' + $obj.data('description') + '</div>');
                        infoWindow.open(map, marker);
                    
                        google.maps.event.addListener(marker, 'click', function () {
                            infoWindow.close();
                        });
                }
            });
        },
        
        getLatLng: function(address, whenGot, region){
            var geo = new google.maps.Geocoder,
                geoRequest = {'address': address};
            
            if(typeof region != 'undefined' && region != ''){
                geoRequest.region = region;
            }
            
            geo.geocode(geoRequest, whenGot);            
        },
        
        carousel: function(){
            var $carousels = $('.carousel');
            $carousels.each(function(){
                var $this = $(this),
                    $items = $this.find('.carousel-item'),
                    $container = $this.find('.carousel-container'),
                    $slider = $this.find('.carousel-slider'),
                    itemWidth = $items.eq(0).outerWidth(true),
                    isSlide = $this.hasClass('slide'),
                    isFade = !isSlide,
                    $bullets = $this.parent().find('.carousel-bullets').children(),
                    hasBullets = $bullets.length > 0,
                    isAuto = $this.hasClass('auto'),
                    autoInterval = null,
                    current = 0,
                    doClearInterval = true,
                    $arrows = $this.parent().children('.arrow'),
                    visibles = isFade ? 1 : parseInt($this.width() / itemWidth),
                    goToItem = function(index){
                        itemWidth = $items.eq(0).outerWidth(true);
                        
                        if(autoInterval != null && doClearInterval){
                            clearInterval(autoInterval);   
                        }
                        
                        var max = 0; //itemWidth * ($items.length - visibles);
                            
                        $items.each(function(){
                            var w = $(this).width();
                            max += w;
                            if(w > itemWidth){
                                itemWidth = w;
                                visibles = isFade ? 1 : parseInt($this.width() / itemWidth);
                            }
                        });
                        
                        if(index < 0) index = $items.length - visibles;
                        else if(index >= $items.length) index = 0;
                        
                        if(isFade){
                            $items.stop(true, true).fadeOut().eq(index).stop(true, true).fadeIn();
                        }else{
                            var res = itemWidth * index;
                            
                            if(res > max){
                                index = 0;
                                res = 0;
                            }
                            
                            $slider.animate({
                                left: -res
                            });
                        }
                        
                        if(hasBullets){
                            $bullets.removeClass('active').eq(index).addClass('active');
                        }
                        
                        current = index;
                    };

                
                if($items.length <= 1){
                    $bullets.hide();
                    $arrows.hide();
                }
                
                $bullets.each(function(eq){
                    var $bullet = $(this);
                    $bullet.click(function(){
                        goToItem(eq);
                    });
                });
                
                $arrows.each(function(){
                    var $arrow = $(this);
                    $arrow.click(function(){
                        goToItem($arrow.hasClass('arrow-left') ? current - 1 : current + 1);
                    });
                });
                
                if(isAuto && $items.length > 1){
                    var it = $this.data('interval');
                    
                    if(typeof it == 'undefined'){
                        it = 5000;
                    }
                    
                    autoInterval = setInterval(function(){
                        doClearInterval = false;
                        goToItem(current + 1);
                        doClearInterval = true;
                    }, it);
                }
            });
        },
        
        burgerMenu: function(){
            var $slicknav = $('#menu-main');
            
            if($slicknav.length === 0) return;
            
            var $menu = $slicknav.find('.menu');
            if($menu.length === 0) return;
            
            $menu.slicknav({
                prependTo: 'body',
                duration: 0,
                beforeOpen: function(trigger){
                    var that = trigger.parent().children('ul');
                    $('.slicknav_menu ul li.slicknav_open ul').each(function(){
                        var $this = $(this);
                        if($this.get(0) != that.get(0)){
                            $this.hide().addClass('slicknav_hidden');
                            $this.parent().removeClass('slicknav_open').addClass('slicknav_collapsed');
                            $this.parent().find('.slicknav_arrow').html('&#9658;');
                        }else{
                            $this.parent().find('.slicknav_arrow').html('&#9660;');
                        }
                    })
                },
                beforeClose: function(trigger){
                    
                }
            });
        }
    };
    
})(jQuery);