/* ==================================================

Custom jQuery functions.

================================================== */


/////////////////////////////////////////////
// NO CONFLICT
/////////////////////////////////////////////

var $ = jQuery.noConflict();


/////////////////////////////////////////////
// LOAD FUNCTIONS
/////////////////////////////////////////////

var onLoad = {
    init: function(){
        nav.init();
        mobileCheck.init();
        slider.init();
        topDrawer.init();
        portfolioSorting.init();
        baseFunctions.init();
    }
};


/////////////////////////////////////////////
// NAVIGATION
/////////////////////////////////////////////

var nav = {
    init: function(){
        var $nav = jQuery('#main-navigation');
        $nav.on('click','li a',function(e){
            var $self = jQuery(this), url = $self.attr('href'),$cont = jQuery('#content');
            if(!($self.parent('').hasClass('current-menu-item'))){
                $nav.find('li').removeClass('current-menu-item current_page_item');
                $self.parent('li').addClass('current-menu-item current_page_item');
            }
        });
        function navHoverIn () {
            $(this).children('ul').slideDown("slow");
            $(this).addClass("down");
        }
        function navHoverOut () {
            $(this).children('ul').slideUp("slow");
            $(this).removeClass("down");
        }
        $("#main-navigation ul li").hoverIntent({
            interval: 100,
            over: navHoverIn,
            timeout: 300,
            out: navHoverOut
            
        });
        $('ul.sub-menu').parent().addClass('parent');
        }   
};


/////////////////////////////////////////////
// SCROLL CONTENT IF MOBILE
/////////////////////////////////////////////

var mobileCheck = {
    init: function() {
        var deviceAgent = navigator.userAgent.toLowerCase();
        var agentID = deviceAgent.match(/(iphone|ipod|android)/);
        if (agentID) {
            $('html,body').not('.home').animate({scrollTop: (jQuery("#content").offset().top) - 10},'slow');
            $(window).scroll(function() {
                var sidebarHeight = $('.side-column').height();
                var windowX = $(window).scrollTop();
                if (windowX > sidebarHeight) {
                    $('.back-to-top').show('fast');
                } else {
                    $('.back-to-top').hide('fast');
                }
            });
        }
        var agentID2 = deviceAgent.match(/(iphone|ipod|ipad|android)/);
        if (!agentID2) {
            $('#resize-me').addClass('show');
        }   
    }
}


/////////////////////////////////////////////
// Flexslider
/////////////////////////////////////////////

var slider = {
    init: function() {
        $('.flexslider').flexslider({
            animation: "fade",             //String: Select your animation type, "fade" or "slide"
            slideDirection: "horizontal",   //String: Select the sliding direction, "horizontal" or "vertical"
            slideshow: true,                //Boolean: Animate slider automatically
            slideshowSpeed: 5000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
            animationDuration: 400,         //Integer: Set the speed of animations, in milliseconds
            directionNav: true,             //Boolean: Create navigation for previous/next navigation? (true/false)
            controlNav: true,               //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
            keyboardNav: true,              //Boolean: Allow slider navigating via keyboard left/right keys
            mousewheel: false,              //Boolean: Allow slider navigating via mousewheel
            prevText: "Previous",           //String: Set the text for the "previous" directionNav item
            nextText: "Next",               //String: Set the text for the "next" directionNav item
            pausePlay: false,               //Boolean: Create pause/play dynamic element
            pauseText: 'Pause',             //String: Set the text for the "pause" pausePlay item
            playText: 'Play',               //String: Set the text for the "play" pausePlay item
            randomize: false,               //Boolean: Randomize slide order
            slideToStart: 0,                //Integer: The slide that the slider should start on. Array notation (0 = first slide)
            animationLoop: true,            //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
            pauseOnAction: true,            //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
            pauseOnHover: false,            //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
            controlsContainer: "",          //Selector: Declare which container the navigation elements should be appended too. Default container is the flexSlider element. Example use would be ".flexslider-container", "#container", etc. If the given element is not found, the default action will be taken.
            manualControls: "",             //Selector: Declare custom control navigation. Example would be ".flex-control-nav li" or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
            start: function(){},            //Callback: function(slider) - Fires when the slider loads the first slide
            before: function(){},           //Callback: function(slider) - Fires asynchronously with each slider animation
            after: function(){},            //Callback: function(slider) - Fires after each slider animation completes
            end: function(){}               //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
        });
    }
}


/////////////////////////////////////////////
// Top Drawer
/////////////////////////////////////////////

var topDrawer = {
    init: function() {
        $(".top-drawer-toggle").click(function () {
            $("#top-drawer").slideToggle("slow");
            if($(this).hasClass('show'))
            {
                $(this).addClass('hide').removeClass('show');
            }
            else
            {
                $(this).addClass('show').removeClass('hide');
            }
        });
    }
}


/////////////////////////////////////////////
// Portfolio Sorting
/////////////////////////////////////////////

var portfolioSorting = {
    init: function() {
        
        (function($) {
            $.fn.sorted = function(customOptions) {
                var options = {
                  reversed: false,
                  by: function(a) { return a.text(); }
                };

                $.extend(options, customOptions);

                $data = $(this);
                arr = $data.get();

                return $(arr);
        
            };

        })($);

        $(function() {

            var read_button = function(class_names) {
                
                var r = {
                    selected: false,
                    type: 0
                };
                
                for (var i=0; i < class_names.length; i++) {
                    
                    if (class_names[i].indexOf('selected-') == 0) {
                        r.selected = true;
                    }
                
                    if (class_names[i].indexOf('segment-') == 0) {
                        r.segment = class_names[i].split('-')[1];
                    }
                };
                
                return r;
                
            };
        
            var sort = function($buttons) {
                var $selected = $buttons.parent().filter('[class*="selected"]');
                return $selected.find('a').attr('data-value');
            };

            // get the first collection
            var $portfolio_items = jQuery('.content-items');

            // clone applications to get a second collection
            var $data = $portfolio_items.clone();

            var $filter_selection = jQuery('#portfolio-filter')

            $filter_selection.each(function(i) {

                var $selection = jQuery(this);
                var $buttons = $selection.find('a');

                $buttons.bind('click', function(e) {
            
                    var $button = jQuery(this);
                    var $button_container = $button.parent();
                    var button_properties = read_button($button_container.attr('class').split(' '));
                    var selected = button_properties.selected;

                    if (!selected) {

                        $buttons.parent().removeClass();
                        $button_container.addClass('selected');

                        var sorting = sort($filter_selection.eq(0).find('a'));

                        if (sorting == 'all') {
                            var $filtered_data = $data.find('li');
                        } else {
                            var $filtered_data = $data.find('li.' + sorting);
                        }

                        var $sorted_data = $filtered_data.sorted({
                            by: function(v) {
                                return $(v).find('strong').text().toLowerCase();
                            }
                        });

                        $portfolio_items.quicksand($sorted_data, {
                          duration: 700,
                          adjustHeight: 'dynamic',
                          easing: 'swing'
                        });
            
                    }
                
                    e.preventDefault();

                });

            });

        });        

    }
}


/////////////////////////////////////////////
// Base Functions
/////////////////////////////////////////////

var baseFunctions = {
    init: function() {

        // Remove title attributes from images to avoid showing on hover
        $('img[title]').each(function() {
            $(this).removeAttr('title');
        });
        
        // Back to top scroll button
        $('.back-to-top').click(function() {
            $('body,html').animate({scrollTop:0},800);
        });
    
        // Image hover state
        $('.wp-post-image').live({
            mouseenter: function() { 
                $(this).not('.single .wp-post-image, .flexslider .wp-post-image').stop().fadeTo(300, 0.3);
            },
            mouseleave: function() {
                $(this).not('.single .wp-post-image, .flexslider .wp-post-image').stop().fadeTo(400, 1);
            }
        });

        // Load Latest Tweets
        $("#tweets").getTwitter({
            userName: "edcousins", // Replace this value with your twitter username
            numTweets: 3,
            loaderText: "Loading tweets...",
            slideIn: false,
            showHeading: false,
            headingText: "",
            showProfileLink: false
        });

        // Load Flickr Photos
        $flickr_id = "37965182@N08";    // Replace this value with your Flickr ID
        $flickr_count = "8"             // The number of photos you want to show

        $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?id=' + $flickr_id + '&lang=en-us&format=json&jsoncallback=?', function(data){
            $.each(data.items, function(i,item){
                if(i < $flickr_count){
                    $("<img class='flickr'/>").attr("src", item.media.m).appendTo("#flickr ul").wrap("<li><a class='flickr-img-link' href='" + item.link + "' target='_blank' title='Flickr'></a></li>");
                }
            });
        });

    }
}


$(document).ready(onLoad.init());