/* ==================================================
Custom jQuery functions.
================================================== */
/////////////////////////////////////////////
// NO CONFLICT
/////////////////////////////////////////////
var $j = jQuery.noConflict();
var onLoad = {
    init: function(){
        page.init();
        nav.init();
        slider.init();
        portfolioSorting.init();
        prettyPhoto.init();
        contactForm.init();
        reloadFunctions.init();
    }
};
/////////////////////////////////////////////
// PAGE FUNCTIONS
/////////////////////////////////////////////
var page = {
init: function () {
        var $content = $j('#content'), $footer_toggle = $j('#footer-toggle'), $footer_widgets = $j('.footer-widgets');
		
        $content.animate({
            opacity:1
        }, 1000, 'easeInOutQuint');
        
        var $state = 'hidden';
                
        $footer_toggle.on('click', function() {        
	        if ($state == 'shown') {
	        	$footer_widgets.slideUp(400);
	      	    $j(this).html('&Show Footer');
	      	    $state = 'hidden';
	        } else {
	            $footer_widgets.slideDown(400);
	            $j('body,html').animate({
	            	scrollTop: $j(document).height()
	            }, 600);
	            $j(this).html('_Hide Footer');
	            $state = 'shown';
	        }
  		});
  		
  		// cache container
        var $blog_container = $j('.masonry-blog-items');
        // initialize isotope
        $blog_container.isotope({
            animationEngine: 'best-available',
            animationOptions: {
                duration: 300,
                easing: 'easeInOutQuad',
                queue: false
            },
            resizable: true,
            layoutMode: 'fitRows'
        });
    }
}
/////////////////////////////////////////////
// NAVIGATION
/////////////////////////////////////////////
var nav = {
    init: function(){
		
		// Main Nav
		$j("ul.sub-menu").parents().addClass('parent');
				
		$j(".menu li.parent").hover(
			function() {
				$j(this).find('ul.sub-menu:first').css("display", "block");
				var $left = "10px";
				if ($j(this).find('ul.sub-menu:first').parent().parent().hasClass("sub-menu")) {
					$left = $j(this).find('ul.sub-menu:first').parent().parent().outerWidth() - 2;
				}
				$j(this).find('ul.sub-menu:first').stop().animate({
					"opacity": "1",
					"left": $left
				}, 200);
		   	},
			function() {
				$j(this).find('ul.sub-menu:first').stop().animate({
					"opacity": "0",
					"left": "-20px"
				}, 200);
				hideNav($j(this).find('ul.sub-menu:first'));
			}
		);
		
        // Mobile Nav
        var $mobile_select = $j('.dropdown-menu'), $selected_page_text = $j('.selected-option');
		$selected_page_text.html($mobile_select.find('option:selected').text());
		
        $mobile_select.change(function() {
            location = $j(this).find("option:selected").val();
        });
    }   
};
/////////////////////////////////////////////
// FLEXSLIDER FUNCTION
/////////////////////////////////////////////
var slider = {
    init: function() {
    	$j('.flexslider').flexslider({
	    	animation: "slide",              //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: 6000,           //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: "[",           //String: Set the text for the "previous" directionNav item
	    	nextText: "]",               //String: Set the text for the "next" directionNav item
	    	pausePlay: true,               //Boolean: Create pause/play dynamic element
	    	pauseText: '5',             //String: Set the text for the "pause" pausePlay item
	    	playText: '4',               //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(){
	   			foresight.reload();
	    	},            //Callback: function(slider) - Fires when the slider loads the first slide
	    	before: function(){
				foresight.reload();
			},           //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)
    	});
    }
}
/////////////////////////////////////////////
// PORTFOLIO SORTING
/////////////////////////////////////////////
var portfolioSorting = {
    init: function() {
        // cache container
        var $container = $j('.filterable-items');
        // initialize isotope
        $container.isotope({
            animationEngine: 'best-available',
            animationOptions: {
                duration: 300,
                easing: 'easeInOutQuad',
                queue: false
            },
            resizable: true,
            layoutMode: 'fitRows'
        });
        
        var $filter_wrap = $j('.filter-wrap'), $portfolio_filter = $j('#portfolio-filter');
        
        // Enable filter options on when there are items from that skill
        $j('.filtering li').each( function() {
        	var $filter = $j(this), $filter_name = $j(this).find('a').attr('class');
        	$j('.portfolio-items li').each( function() {
        		if ( $j(this).hasClass($filter_name) ) {
        			$filter.addClass('has-items');
        		}
        	});
        });
        
        $filter_wrap.on('click', 'a.select', function(e) {
        	e.preventDefault();
        	$portfolio_filter.css( 'top', ($filter_wrap.outerHeight() + 4) + 'px' );
        	$portfolio_filter.slideToggle(400);
        });
        // filter items when filter link is clicked
        $j('.filtering li a').on('click', function() {
            $j('.filtering li').removeClass('selected');
            $portfolio_filter.slideUp(400);
            $j(this).parent().addClass('selected');
            var selector = $j(this).attr('data-filter');
            $container.isotope({ filter: selector });
            return false;
        });
    }
}
/////////////////////////////////////////////
// PRETTYPHOTO FUNCTION
/////////////////////////////////////////////
var prettyPhoto = {
    init: function() {
		
		var deviceAgent = navigator.userAgent.toLowerCase();
		var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
		if (agentID) {
			$j("a[data-gal^='prettyPhoto']").on("click", function(e) {
				e.preventDefault();
			});
		} else {
	        $j("a[data-gal^='prettyPhoto']").prettyPhoto({
	            animation_speed: 'fast', /* fast/slow/normal */
	            slideshow: 5000, /* false OR interval time in ms */
	            autoplay_slideshow: false, /* true/false */
	            opacity: 0.80, /* Value between 0 and 1 */
	            show_title: true, /* true/false */
	            allow_resize: true, /* Resize the photos bigger than viewport. true/false */
	            default_width: 500,
	            default_height: 344,
	            counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
	            // theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
	            horizontal_padding: 20, /* The padding on each side of the picture */
	            hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
	            wmode: 'opaque', /* Set the flash wmode attribute */
	            autoplay: true, /* Automatically start videos: True/False */
	            modal: false, /* If set to true, only the close button will close the window */
	            deeplinking: false, /* Allow prettyPhoto to update the url to enable deeplinking. */
	            overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
	            keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
	            changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
	            callback: function(){}, /* Called when prettyPhoto is closed */
	            ie6_fallback: true
	        });
        }
    }
}
/////////////////////////////////////////////
// CONTACT FORM FUNCTION
/////////////////////////////////////////////
var contactForm = {
    init: function() {
        $j('form#contactForm').submit(function() {
            
            $j('form#contactForm label.error').remove();
            $j('form#contactForm span.error').remove();
            var hasError = false;
            
            $j('.requiredField').each(function() {
                $this = $j(this);
                if($j.trim($this.val()) == '') {
                    $this.addClass('invalid');
                    hasError = true;
                } else if($this.hasClass('email-input')) {
                    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                    if(!emailReg.test($j.trim($this.val()))) {
                        $this.addClass('invalid');
                        hasError = true;
                    } else {
                        $this.removeClass('invalid');
                    }
                } else {
                    $this.removeClass('invalid');
                }
            });
            
            if(!hasError) {
                $j('form#contactForm li.buttons button').fadeOut('normal', function() {
                    $j(this).parent().append('');
                });
                var formInput = $j(this).serialize();
                $j.post($j(this).attr('action'),formInput, function(data){
                    $j('form#contactForm').slideUp("fast", function() {                
                        $j('p.thanks').fadeIn(1000);
                    });
                });
            }
            
            return false;
            
        });
    }
}
/////////////////////////////////////////////
// RELOAD FUNCTIONS
/////////////////////////////////////////////
var reloadFunctions = {
    init:function() {
        // Remove title attributes from images to avoid showing on hover 
        $j('img[title]').each(function() {
            $j(this).removeAttr('title');
        });
		
		// Button hover tooltips
		$j('.tooltip').each( function() {
			$j(this).css( 'marginLeft', '-' + Math.round( ($j(this).outerWidth() / 2) ) + 'px' );
		});
		
		$j('.tweet-details a').hover( function() {
			$j(this).parent().find('.tooltip' ).stop().animate({
				bottom: '36px',
				opacity: 1
			}, 400, 'easeInOutExpo');
		}, function() {
				$j(this).parent().find('.tooltip').stop().animate({
					bottom: '20px',
					opacity: 0
				}, 400, 'easeInOutExpo');
		});
		
        // Tabs Shortcode Function
        $j('.tabbed-asset').tabs();
        
        // Accordion Shortcode Function
        $j('.accordion').accordion({
            collapsible: true,
            autoHeight: false
        });
    }
}
function hideNav($subnav) {
	setTimeout(function() {
		if ($subnav.css("opacity") == "0") {
			$subnav.css("display", "none");
		}
	}, 300);
}
$j(document).ready(onLoad.init);
/////////////////////////////////////////////
// GOOGLE WEB FONT FUNCTION
/////////////////////////////////////////////
WebFontConfig = {
    google: { families: [ 'Gentium Basic'] }
};
(function() {
    var webfontscript = document.createElement('script');
    webfontscript.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    webfontscript.type = 'text/javascript';
    webfontscript.async = 'true';
    var script = document.getElementsByTagName('script')[0];
    script.parentNode.insertBefore(webfontscript, script);
})();