﻿var tweetUsers = ['extragenc','mashable'];
var buildString = "";
//var FBAppID = '183531065032926';
var FBAppID = '301129113239556';


// Creating custom :external selector
$.expr[':'].external = function (obj) {
    return (obj.hostname != location.hostname);
};


$(document).ready(function () {

    var userAgent = navigator.userAgent;
    var isHandle = false;

    if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
        // iPad or iPhone
        isHandle = true;
    }

    var $body = $('body');
    var $hash = window.location.hash;
    var accordionPanel;

    // sk: this solution will only work if deployed from the root of the server
    var HOSTURL = window.location.host;
    var BASEURL = "http://" + HOSTURL + '/';

    //extratest.garantilab.com
    if (HOSTURL == 'extratest.garantilab.com') {
        FBAppID = '295780360436687';
    }


    // Bind an event to window.onhashchange that, when the hash changes, gets the
    // hash and adds the class "selected" to any matching nav link.
    $(window).hashchange(function () {
        var hash = location.hash;
        //alert(location.pathname + location.search + location.hash.replace("#!/", ""));

        _gaq.push(['_trackPageview', location.pathname + location.search + location.hash.replace("#!/", "")]);

        // Set the page title based on the hash.
        //document.title = 'The hash is ' + (hash.replace(/^!#/, '') || 'blank') + '.';

        // Iterate over all nav links, setting the "selected" class as-appropriate.
        //$('nav a').each(function () {
        //    var that = $(this);
        //    that[that.attr('href') === hash ? 'addClass' : 'removeClass']('selected');
        //});
    })

    // Since the event is only triggered when the hash changes, we need to trigger
    // the event now, to handle the hash the page may have loaded with.
    $(window).hashchange();


    // Facebook SDK
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=" + FBAppID;
        //js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=295780360436687";
        fjs.parentNode.insertBefore(js, fjs);
    } (document, 'script', 'facebook-jssdk'));

    var _x = window.location.toString().split(BASEURL).join('');
    var substr = _x.split('#!/');
    _x = substr[1];

    $(window).load(function () {
        //$('#loader').fadeOut();
        if ($hash != '') {
            $('#' + _x + '').find($('[role="tab"]')).trigger('click');
        }

        resizeBackground();

    });


    // Add 'external' CSS class to all external links
    $('a:external').addClass('external');


    /*! Cufon Replace
    ---------------------------------------------- */
    if ($.browser.msie && $.browser.version.substr(0, 1) < 10) {
        Cufon.replace('.bannerText h2 span');
    }

    /*! Application
    ---------------------------------------------- */
    //$.app.external();                   // External links
    $.app.nav();                        // Highlights the current in a menu
    $.app.fbShare();                    // Facebook share button
    $.app.parallax();                   // Parallax background
    $("#tabs").organicTabs();           // Tabs


    /*! Floating Panel
    ---------------------------------------------- */
    //$('#sidebar').portamento({ wrapper: $('#content'), gap: 10 });
    //$('.top').addClass('hidden');
    $.waypoints.settings.scrollThrottle = 30;
    $('#container').waypoint(function (event, direction) {
        //$('.top').toggleClass('hidden', direction === "up");
    }, {
        offset: '-100%'
    }).find('#sidebar-holder').waypoint(function (event, direction) {
        $(this).parent().toggleClass('sticky', direction === "down");
        event.stopPropagation();
    });


    /*! Accordion
    ---------------------------------------------- */
    $('[role="tab"]').click(function (e) {
        //e.preventDefault();

        $this = $(this);
        // Find the parent item of accordion panel
        accordionPanel = $this.closest('[role="accordion"]');
        $this.toggleClass('current');
        $this.next().slideToggle(function () {
            // Check if this accordion panel is expanded
            if ($this.hasClass('current')) {
                // Scroll to top of the expanded panel
                if (!isHandle) {
                    $.scrollTo(accordionPanel, 500);
                }
            }
            // Call resize background funtion after slide complete
            if (!isHandle) {
                resizeBackground();
            }
        });

        //return false;
    }).next().hide(); // Hide accordion panels on load

    $('[role="trigger"]').click(function () {
        // Trigger accordion button to collapse the panel
        $(this).parents('[role="accordion"]').find($('[role="tab"]')).trigger('click');
        //window.location.hash = this.hash;

        //return false;
    });



    /*! Resize Background Image
    ---------------------------------------------- */
    function resizeBackground() {
        $('#background').height($body.height());
    };
    if (!isHandle) {
        resizeBackground();
    }


    /*! Twitter Ticker
    ---------------------------------------------- */
    $("#tweet-container").getTwitter({
        userName: "extragenc",
        numTweets: 25,
        loaderText: "Loading tweets...",
        slideIn: true,
        slideDuration: 750,
        showHeading: true,
        headingText: "Latest Tweets",
        showProfileLink: true,
        showTimestamp: true
    });

    //$('#tweet-container').jScrollPane();


});           // document ready


(function($) {
    $.app = {
        external: function(_el) {
            var _2d = {
                selector: "a"
            };
            if (typeof _el == "string") {
                _2d.selector = _el;
            }
            var _el = $.extend(_2d, _el);
            var _2e = window.location.hostname;
            _2e = _2e.replace("www.", "").toLowerCase();
            return $(_el.selector).each(function() {
                var _2f = $(this).attr("href").toLowerCase();
                if (_2f.indexOf("http://") != -1 && _2f.indexOf(_2e) == -1) {
                    $(this).attr("target", "_blank");
                    $(this).addClass("external");
                }
            });
        },
        nav: function(_el) {
            // Highlights the current in a menu by comparing the links to the current URL path
            var path = location.pathname.substring(1);
            if (path)
                $('nav a[href$="' + path + '"]').attr('class', 'active');
        },
        fbShare: function(_el) {
            // Facebook Like Box Plugin
	        $('[role="fb-share"]').live('click', function(e){
		        e.preventDefault();
		        $this = $(this);
		
		        var $fbShare = {}
			        $fbShare.method = $this.data('method'),
			        $fbShare.name = $this.data('name'),
			        $fbShare.link = $this.data('link'),
			        $fbShare.picture = $this.data('picture'),
			        $fbShare.caption = $this.data('caption'),
			        $fbShare.description = $this.data('description');
		        FB.ui({
			        method: $fbShare.method,
			        name: $fbShare.name,
			        link: $fbShare.link,
			        picture: $fbShare.picture,
			        caption: $fbShare.caption,
			        description: $fbShare.description
		        });
	        });
        },
        parallax: function(_el) {
            /*! Parallax Scrolling
            ---------------------------------------------- */
	        // Cache the Window object
	        $window = $(window);

	        // Cache the Y offset and the speed of each sprite
	        $('[data-type]').each(function() {	
		        $(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
		        $(this).data('Xposition', $(this).attr('data-Xposition'));
		        $(this).data('speed', $(this).attr('data-speed'));
	        });
	
	        // For each element that has a data-type attribute
	        $('section[data-type="background"]').each(function(){
	
	
		        // Store some variables based on where we are
		        var $self = $(this),
			        offsetCoords = $self.offset(),
			        topOffset = offsetCoords.top;
		
		        // When the window is scrolled...
	            $(window).scroll(function() {
	
			        // If this section is in view
			        if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
				         ( (topOffset + $self.height()) > $window.scrollTop() ) ) {
	
				        // Scroll the background at var speed
				        // the yPos is a negative value because we're scrolling it UP!								
				        var yPos = -($window.scrollTop() / $self.data('speed')); 
				
				        // If this element has a Y offset then add it on
				        if ($self.data('offsetY')) {
					        yPos += $self.data('offsetY');
				        }
				
				        // Put together our final background position
				        var coords = '50% '+ yPos + 'px';

				        // Move the background
				        $self.css({ backgroundPosition: coords });
				
				        // Check for other sprites in this section	
				        $('[data-type="sprite"]', $self).each(function() {
					
					        // Cache the sprite
					        var $sprite = $(this);
					
					        // Use the same calculation to work out how far to scroll the sprite
					        var yPos = -($window.scrollTop() / $sprite.data('speed'));					
					        var coords = $sprite.data('Xposition') + ' ' + (yPos + $sprite.data('offsetY')) + 'px';
					
					        $sprite.css({ backgroundPosition: coords });													
					
				        }); // sprites
			
				        // Check for any Videos that need scrolling
				        $('[data-type="video"]', $self).each(function() {
					
					        // Cache the video
					        var $video = $(this);
					
					        // There's some repetition going on here, so 
					        // feel free to tidy this section up. 
					        var yPos = -($window.scrollTop() / $video.data('speed'));					
					        var coords = (yPos + $video.data('offsetY')) + 'px';
	
					        $video.css({ top: coords });													
					
				        }); // video	
			
			        }; // in view
	
		        }); // window scroll
			
	        });	// each data-type
        },
        resizeBackground: function(_el) {
            
        }
     };
})(jQuery);
