/* Author:
 Adaptive Themes
 */

(function(w, d, s) {
    function go() {
        var js, fjs = d.getElementsByTagName(s)[0], load = function(url, id) {
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement(s);
            js.src = url;
            js.id = id;
            fjs.parentNode.insertBefore(js, fjs);
        };

        load('//connect.facebook.net/en_US/all.js#xfbml=1', 'fbjssdk');
        load('//platform.twitter.com/widgets.js', 'tweetjs');

        function setup_twitter_feeds() {
            //get the .twitter-feed elements
            //get the tweet() params from data-* attributes

            var feeds = $('.twitter-feed');
            feeds.each(function() {
                var f = $(this);
                var usr = f.attr('data-usr');
                var count = parseInt(f.attr('data-count'));

                f.tweet({
                    username: usr,
                    count: count,
                    template: "{avatar}{join}{text}{time}"
                });
            });
        }

        setup_twitter_feeds();
    }

    if (w.addEventListener) {
        w.addEventListener("load", go, false);
    }
    else if (w.attachEvent) {
        w.attachEvent("onload", go);
    }
}(window, document, 'script') );

// Add outerHTML helper
jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

/*
 Configure Isotope in the Load function
 */
jQuery(window).load(function($) {
    setupIsotope();
});

var isAndroid = false;
function fixPreviewHeights() {
    var topBarHeight = $('#preview-top-bar').height();
    jQuery("#preview-frame").attr("height", (jQuery(window).height() - topBarHeight) + 'px');
}

function configureSlider() {
    var $images = $('.frontpageslider ul > li:not(.clone) > a > img');
    var allDownloaded = true;
    for (var i = 0; i < $images.length; i++) {
        allDownloaded = $images.get(i).complete;
    }
    if (allDownloaded) {
        initFrontpageSlider();       
    } else {
        window.setTimeout(configureSlider, 100);
    }
}

function update_ie8_shadow() {
    var bodyWidth = $('body').width();
    if ($('html.ie8').length > 0) {
        var windowWidth = $(window).width();
        var padding = (windowWidth - bodyWidth) / 2;
        if (padding < 0) padding = 0;
        $('body').css('padding-left', padding);
        $('body').css('padding-right', padding);
    }
}

function _getOffset(elm, height) {
	var cStyle = elm.ownerDocument && elm.ownerDocument.defaultView && elm.ownerDocument.defaultView.getComputedStyle
		&& elm.ownerDocument.defaultView.getComputedStyle(elm, null),
		ret = cStyle && cStyle.getPropertyValue(height ? 'height' : 'width') || '';
	if (ret && ret.indexOf('.') > -1) {
		ret = parseFloat(ret)
			+ parseInt(cStyle.getPropertyValue(height ? 'padding-top' : 'padding-left'))
			+ parseInt(cStyle.getPropertyValue(height ? 'padding-bottom' : 'padding-right'))
			+ parseInt(cStyle.getPropertyValue(height ? 'border-top-width' : 'border-left-width'))
			+ parseInt(cStyle.getPropertyValue(height ? 'border-bottom-width' : 'border-right-width'));
	} else {
		ret = height ? elm.offsetHeight : elm.offsetWidth;
	}
	return ret;
}
function getOffsetWidth(elm) {
	return _getOffset(elm);
}
function getOffsetHeight(elm) {
	return _getOffset(elm, true);
}

function flexsliderAnimateIn() {

    if($('#frontpageslider').length > 0) {
        var $images = $('.frontpageslider ul > li:not(.clone):first > a > img');
        var height = $images.get(0).height;
        var width = $images.get(0).width;
        // Needed for IE
        if(height == 0) { 
            height = $('.frontpageslider ul > li').height();
        }
        if(height == 0) {
            height = 420;
        }
        if(width == 0) {
            width = $('.frontpageslider ul > li').width();
        }
        if($('#frontpageslider').width() < 1024) {
            height = $('#frontpageslider').width()/width * height;
        }
        
        $('.frontpageslider > div:first-child').fadeOut(500, function() {
            $('.frontpageslider').animate({height: height}, 500, function() {
                $('.frontpageslider ul').animate({opacity: 1}, 1000, function() {
                    $(this).css('position', 'relative');
                    $('.frontpageslider').css('height', 'auto');
                });
            });
        }); 
    }
}

function initFrontpageSlider() {

    var fpsDiv = jQuery('.frontpageslider');
    var slideshowAttr = fpsDiv.attr('data-slideshow');
    var slideshow = false;
    if (typeof slideshowAttr !== 'undefined' && slideshowAttr !== false) {
        slideshow = true;
    }

    var slideshowSpeed = parseInt(fpsDiv.attr('data-slideshow-speed'));
    if (isNaN(slideshowSpeed) || typeof slideshowSpeed === 'undefined' || slideshowSpeed === false || slideshowSpeed < 1) {
        slideshowSpeed = 7000;
    }

    fpsDiv.flexslider({
        animation: 'slide',
        slideshow: slideshow,
        slideshowSpeed: slideshowSpeed,
        directionNav: false
    });
    
    flexsliderAnimateIn();
}

jQuery(document).ready(function($) {

    configureSlider();

    jQuery('.galleryslider').flexslider({
        animation: 'slide',
        slideshow: false,
        directionNav: false
    });

    $('ul.latest-projects > li.slide > a > img').attr('height', 'auto').attr('width', 'auto');

    $("#mobile-nav").change(function() {
        window.location = $(this).find("option:selected").val();
    });

    /* Set the selected option to the current page */
    $("#mobile-nav > select ").val('');

    update_ie8_shadow();
    var bodyWidth = $('body').width();
    $(window).resize(function() {
        update_ie8_shadow();
        if (latestShortcodeScrollView != null) {
            if (bodyWidth < 767) {
                latestShortcodeScrollView.enable();
            } else {
                latestShortcodeScrollView.pages.set('index', 0);
                latestShortcodeScrollView.disable();
            }
        }

    });

    // For use within normal web clients
    var isiPod = navigator.userAgent.match(/iPod/i) != null;
    var isiPad = navigator.userAgent.match(/iPad/i) != null;
    var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
    var isMobileSafari = isiPod || isiPad || isiPhone;

    var ua = navigator.userAgent.toLowerCase();
    isAndroid = ua.indexOf("android") > -1;

//  Mobile Framebuster
//    if (parent.frames.length > 0 && (isMobileSafari || isAndroid)) {
//        top.location.href = self.location.href;
//    }


    if (isMobileSafari || isAndroid) {

        androidClient = isAndroid;
        if (isAndroid) {
            $('.native-video > video').removeAttr('controls');
        }

        jQuery(".native-video").slideToggle(1000, function() {
            $(this).find('video').delay(200).animate({opacity: 1}, 1000, function() {
                if (isAndroid) {
                    var overlayTop = ($('.native-video').height() - 74) / 2;
                    $('.native-video').append('<div class="video-overlay" style="top:' + overlayTop + 'px;"></div>');
                }
            });
        });

        if (isAndroid) {
            $('.native-video').addClass('android');

            //play logic for android
            var video = $('.native-video > video');
            video.click(function() {
                $(this).get(0).play();
            });
        }
    }
    else if (jQuery().jPlayer) {
        jQuery(".jp-video-container").css('display', 'block');

        jQuery('.root-jplayer').each(function() {
            var m4v = $(this).attr('data-m4v');
            var ogv = $(this).attr('data-ogv');
            var webm = $(this).attr('data-webm');
            var poster = $(this).attr('data-poster');
            var interface = '#' + $(this).attr('data-interface');
            var swf = $(this).attr('data-swf');
            $(this).jPlayer({
                ready: function () {
                    jQuery(this).jPlayer("setMedia", {
                        m4v: m4v,
                        ogv: ogv,
                        webmv: webm,
                        poster: poster
                    });
                },
                swfPath: swf,
                cssSelectorAncestor: interface,
                supplied: "m4v, ogv,  webm",
                size: {width:'100%' }
            });
        });
    }

    if (isMobileSafari || isAndroid) {
        jQuery(".jp_interface").addClass('no-volume');
    }

    jQuery('.root-jplayer-audio').each(function() {
        var mp4 = $(this).attr('data-mp4');
        var ogg = $(this).attr('data-ogg');
        var interface = '#' + $(this).attr('data-interface');
        var swf = $(this).attr('data-swf');
        //Instantiate jPlayer Audio
        jQuery(this).jPlayer({
            ready: function () {
                jQuery(this).jPlayer("setMedia", {
                    mp3: mp4,
                    oga: ogg,
                    end: ""
                });
            },
            swfPath: swf,
            cssSelectorAncestor: interface,
            supplied: "oga,mp3, all",
            size: {width:'100%' }
        });
    });


    $('div.video-overlay').live('click', function() {
        var video = $('.native-video > video');
        video.click();
    });


    $(".alert-message").alert();

    $('.tabs').tabs()
    $('.tabs').bind('change', function (e) {
        e.target // activated tab
        e.relatedTarget // previous tab

        $(e.target).parent().siblings().removeClass('right-of-active');
        $(e.target).parent().next().addClass('right-of-active');
    })
    $('.tabs li.active').each(function() {
        $(this).next().addClass('right-of-active');
        paneSelector = $(this).find('a').first().attr('href');
        $(paneSelector).addClass('active');
    });

    //Isotope Aux functionality
    $('#portfolio-shuffle').click(function(event) {
        event.preventDefault();
        $('#masonry-container').isotope('shuffle', function() {
        });
    });


    // Mobile Portfolio Filter Container
    setupHorizontalScrollview();
    //Preview Height
    fixPreviewHeights();

    $(window).resize(function() {
        /* Scrollview */
        if (filterScrollView == null) {
            setupHorizontalScrollview();
        }
        else {
            $('#scrollview-container').css("width", $(this).width() - 10);
        }
        /* Portfolio */
        setupIsotope();
        
        /* Android Overlay Positioning */
        checkVideoOverlay();
        
        /* Check Twipsy */
        checkTwipsy();

        //Preview Height
        fixPreviewHeights();

        setupPortfolioLinks();
    });

    setupPortfolioLinks();

    checkTwipsy();

    // Prevent iOS from zooming in on elements on focus
    var $viewportMeta = $('meta[name="viewport"]');
    $('input, select, textarea').bind('focus blur', function(event) {
        $viewportMeta.attr('content', 'width=device-width,initial-scale=1,maximum-scale=' + (event.type == 'blur' ? 10 : 1));
    });

    // Set up searchbox focus
    $('.search-widget input[type="text"]').focusin(function() {
        $(this).closest('fieldset').addClass('has-focus');
    });
    $('.search-widget input[type="text"]').focusout(function() {
        $(this).closest('fieldset').removeClass('has-focus');
    });

    // Mobile menu
    // Clone the menu and remove any sf-menu and #topmenu id css by removing the class and id
    $('#mobile-menu-modal > div.modal-body').html($("ul#topmenu").clone().removeClass('sf-menu').attr("id", "mobile-nav-ul"));
    $('#mobile-menu-modal').modal({ backdrop: true, keyboard: true});
    $('a.mobile-menu').click(function() {
        $('#mobile-menu-modal').modal('show');
    });

    $("ul#topmenu").superfish({
        delay: 200,
        animation: {opacity:'show', height:'show'},
        speed: 'fast',
        autoArrows: false,
        dropShadows: false
    });

});

function checkVideoOverlay() {
    if (isAndroid) {
        $('.video-overlay').each(function() {
            var overlayTop = ($('.native-video').height() - 74) / 2;
            $(this).css('top', overlayTop + 'px');
        });
    }
}

function checkTwipsy() {
    if ($('html.touch').length != 0) {
        $('#portfolio-shuffle, #portfolio-gallery, #scrollview-prev, #scrollview-next').attr('data-original-title', '');
    }
}

var oldLinkWidth = '0';
var prettyPhotoSetup = false;
function setupPortfolioLinks() {
    var windowWidth = $(window).width();
    if ($('div#masonry-container > article').length > 0 && windowWidth != oldLinkWidth) {

        if (windowWidth < 767) {
            //Mobile behavior
            //register a callback that intersects the <a> trigger on the image
            var ppArticles = $("div#masonry-container > article > a[rel^='prettyphoto']");
            if (ppArticles.length > 0) {

                ppArticles.unbind('click');
                prettyPhotoSetup = false;

                ppArticles.bind('click', function(e) {
                    e.preventDefault();
                    var newHref = $(this).attr('data-item-href');
                    top.location.href = newHref;
                });

            }
        }
        else {
            //Tablet and Fullsize behavior
            if (!prettyPhotoSetup) {
                var ppArticles = $("div#masonry-container > article > a[rel^='prettyphoto']");
                if (ppArticles.length > 0) {
                    ppArticles.unbind('click');
                }
                $("a[rel^='prettyphoto']").prettyPhoto({
                    animationSpeed : 'fast',
                    slideshow : 5000,
                    show_title : false,
                    overlay_gallery : false,
                    deeplinking: false,
                    social_tools: false
                });
            }
        }
    }

    oldLinkWidth = windowWidth;
}

var isotopeInitialized = false;
var oldWidth = '0';
function setupIsotope() {

    // return;

    var windowWidth = $(window).width();

    if ($('div#masonry-container').length > 0 && (scopeInitialized = false || windowWidth != oldWidth)) {

        // Get Measurements
        var gutterWidth, columnWidth, layoutMode = 'masonry';
        if (windowWidth > 767 || $('html.ie8').length > 0) {
            $('div#masonry-container').removeClass('isMobile');
            columnWidth = 220;
            gutterWidth = 20;
            $('div#masonry-container > article.item, div#masonry-container > article.item img').css('width', columnWidth - 2);
            // PrettyPhoto Rollovers
            $('article.item > a:first-child > img').each(function() {
            });
            if (filterScrollView != null) {
                filterScrollView.disable();
            }

        }
        else {
            /* 2 wide */
            $('div#masonry-container').addClass('isMobile');
            var portfolioWidth = $('div#masonry-container').width();

            gutterWidth = 14;
            columnWidth = Math.floor((portfolioWidth - gutterWidth) / 2);
            itemHeight = Math.floor(columnWidth / 1.618);
            $('div#masonry-container > article.item, div#masonry-container > article.item img').css('width', columnWidth);
            $('div#masonry-container > article.item, div#masonry-container > article.item img').attr('height', 'auto');
            masonryWidth = gutterWidth * 3 + columnWidth * 2;
            containerWidth = $('#masonry-container').width();
            if (masonryWidth > containerWidth) {
                gutterWidth--;
            }
            else {
                gutterWidth = gutterWidth - (windowWidth - masonryWidth);
            }

            // Enable filters
            if (filterScrollView != null) {
                filterScrollView.enable();
            }
        }

        if (isotopeInitialized == false) {
            // modified Isotope methods for gutters in masonry
            setupIsotopeGutterWidth();
            $('div#masonry-container').isotope({
                itemSelector : 'div#masonry-container > article.item',
                layoutMode: layoutMode,
                masonry: {
                    columnWidth: columnWidth,
                    gutterWidth: gutterWidth
                }
            });

            var applyIsotopeFilter = function(selector) {
                $('ul#filters > li > a.current, ul#mobile-filters > li > div.current').removeClass('current');
                /* Add current class to the applied the normal and mobile filter links */
                $('ul#filters > li > a[data-filter="' + selector + '"], ul#mobile-filters > li > div[data-filter="' + selector + '"]').addClass('current');
                /* Apply filter */
                $('div#masonry-container').isotope({ filter: selector });
                /* Prevent browser from navigating to '#' */
                return false;
            };

            $('ul#filters > li, ul#mobile-filters > li').click(function(e) {
                /* Retrieve data filter */
                var selector = $(this).children('li > div, li > a').attr('data-filter');
                /* Remove current class from both the normal and mobile filter links */
                return applyIsotopeFilter(selector);
            });

            $('ul#mobile-filters > li > div').click(function(e) {
                var selector = $(this).attr('data-filter');
                return applyIsotopeFilter(selector);
            });

            isotopeInitialized = true;
            $('#masonry-container article.item').css({'display':'block'}).animate({opacity:1}, 800);

        }
        else {
            $('div#masonry-container').isotope('option', {
                itemSelector : 'div#masonry-container > article.item',
                layoutMode: layoutMode,
                masonry: {
                    columnWidth: columnWidth,
                    gutterWidth: gutterWidth
                }
            });
            $('div#masonry-container').isotope('reLayout');
        }
    }

    oldWidth = windowWidth;
}


function setupIsotopeGutterWidth() {
    // modified Isotope methods for gutters in masonry
    $.Isotope.prototype._getMasonryGutterColumns = function() {
        var gutter = this.options.masonry && this.options.masonry.gutterWidth || 0;
        containerWidth = this.element.width();

        this.masonry.columnWidth = this.options.masonry && this.options.masonry.columnWidth ||
            // or use the size of the first item
            this.$filteredAtoms.outerWidth(true) ||
            // if there's no items, use size of container
            containerWidth;

        this.masonry.columnWidth += gutter;

        this.masonry.cols = Math.floor(( containerWidth + gutter ) / this.masonry.columnWidth);
        this.masonry.cols = Math.max(this.masonry.cols, 1);
    };

    $.Isotope.prototype._masonryReset = function() {
        // layout-specific props
        this.masonry = {};
        // FIXME shouldn't have to call this again
        this._getMasonryGutterColumns();
        var i = this.masonry.cols;
        this.masonry.colYs = [];
        while (i--) {
            this.masonry.colYs.push(0);
        }
    };

    $.Isotope.prototype._masonryResizeChanged = function() {
        var prevSegments = this.masonry.cols;
        // update cols/rows
        this._getMasonryGutterColumns();
        // return if updated cols/rows is not equal to previous
        return ( this.masonry.cols !== prevSegments );
    };
}

var filterScrollView, latestWidgetScrollView, latestShortcodeScrollView;
function setupHorizontalScrollview() {

    // Detect if Android
    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");

    if (filterScrollView == null && $('#scrollview-container').css('display') == 'block' && $('#scrollview-container').css('visibility') == 'visible') {

        YUI().use('scrollview', function(Y) {

            filterScrollView = new Y.ScrollView({
                id: 'scrollview',
                srcNode: '#scrollview-content',
                flick: {
                    minDistance:10,
                    minVelocity:0.3,
                    axis: "x"
                }
            });

            filterScrollView.render();
        });

        // Keep the width of the scrollview container equal to the width of the page
        $('#scrollview-container').css("width", $(this).width());

    } else {
        if (filterScrollView != null) filterScrollView.render();
    }

    // LATEST PROJECTS SLIDER
    if (typeof YUI != 'undefined' && latestShortcodeScrollView == null) {
        YUI().use('scrollview', 'scrollview-paginator', function(Y) {

            latestShortcodeScrollView = new Y.ScrollView({
                id: 'lp-sc-slider',
                srcNode: '.latest-projects-shortcode-slides',
                flick: {
                    minDistance:10,
                    minVelocity:0.3,
                    axis: "x"
                }
            });
            if(!isAndroid) {
                // This fix doesn't work in ICS
                latestShortcodeScrollView._prevent.move = false;
            }
            latestShortcodeScrollView.plug(Y.Plugin.ScrollViewPaginator, {
                selector: 'li'
            });
            latestShortcodeScrollView.render();


            var content = latestShortcodeScrollView.get("contentBox");

            content.delegate("click", function(e) {
                // For mouse based devices, we need to make sure the click isn't fired
                // at the end of a drag/flick. We use 2 as an arbitrary threshold.
                if (Math.abs(latestShortcodeScrollView.lastScrolledAmt) < 2) {
                    //on click logic
                }
            }, "img");

            // Prevent default image drag behavior
            content.delegate("mousedown", function(e) {
                e.preventDefault();
            }, "img");

            var bodyWidth = $('body').width();
            if (latestShortcodeScrollView != null) {
                if (bodyWidth < 767) {
                    latestShortcodeScrollView.enable();
                } else {
                    latestShortcodeScrollView.disable();
                }
            }

        });
    }


    //LATEST PROJECTS WIDGET
    if (typeof YUI != 'undefined' && latestWidgetScrollView == null) {

        YUI().use('scrollview', 'scrollview-paginator', function(Y) {
            latestWidgetScrollView = new Y.ScrollView({
                id: 'lp-slider',
                srcNode: '.slides_container',
                flick: {
                    minDistance:10,
                    minVelocity:0.3,
                    axis: "x"
                }
            });
            if(!isAndroid) {
                // This fix doesn't work in ICS
                latestWidgetScrollView._prevent.move = false;
            }
            latestWidgetScrollView.plug(Y.Plugin.ScrollViewPaginator, {
                selector: 'li'
            });
            $('#latest-projects-slider .latest-projects > li.slide').css('display', 'inline-block');
            latestWidgetScrollView.render();

            var content = latestWidgetScrollView.get("contentBox");

            content.delegate("click", function(e) {
                // For mouse based devices, we need to make sure the click isn't fired
                // at the end of a drag/flick. We use 2 as an arbitrary threshold.
                if (Math.abs(latestWidgetScrollView.lastScrolledAmt) < 2) {
                    //on click logic
                }
            }, "img");

            // Prevent default image drag behavior
            content.delegate("mousedown", function(e) {
                e.preventDefault();
            }, "img");

            $('#scrollview-next').bind('click', function(e) {
                e.preventDefault();
                var orig_index = latestWidgetScrollView.pages.get('index');
                var next_ret_val = latestWidgetScrollView.pages.next();
                var new_index = latestWidgetScrollView.pages.get('index');

                if (orig_index == new_index) {
                    latestWidgetScrollView.pages.set('index', 0);
                }
            });

            $('#scrollview-prev').bind('click', function(e) {
                e.preventDefault();
                var orig_index = latestWidgetScrollView.pages.get('index');
                latestWidgetScrollView.pages.prev();
                var new_index = latestWidgetScrollView.pages.get('index');

                if (orig_index == new_index) {
                    latestWidgetScrollView.pages.set('index', latestWidgetScrollView.pages.get('total') - 1);
                }
            });

        });
    }
}
