/* Author Matthew Geddert
 * Copyright 2010 Matthew Geddert (geddert.com)
 * Licensed under GNU General Public License: http://www.gnu.org/licenses/
 */

function supports_html5_h264() {
    if (!document.createElement('video').canPlayType) { return false; }
    var v = document.createElement("video");
    return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}
var method = 'do-nothing';
if(vimeo_loads==true) {
  method = 'vimeo';
} else if(supports_html5_h264()) {
  method = 'html5';
} else if (swfobject.getFlashPlayerVersion().major >= 9) {
  method = 'flash-local';
}

function play_video(link) {
    var vid = $(link);
    var poster = $('img', $(link));
    if(method=='vimeo') {
        vid.oembed('http://vimeo.com/'+vid.attr('id'), {
            embedMethod: 'replace',
            width: poster.attr('width'),
            height: poster.attr('height'),
            vimeo: {autoplay: true, width: poster.attr('width'), height: poster.attr('height')}
        });
    } else if(method=='html5') {
        vid.replaceWith($('<video></video>').attr({ height: poster.attr('height'), width: poster.attr('width'), poster: poster.attr('src'), controls: 1, autoplay: 1}).append($('<source></source>').attr({ src: vid.attr('href'), type: 'video/mp4'})));
    } else if(method=='flash-local') {
          $('#'+$(link).attr('id')+'_wrapper').css('height', poster.attr('height')).css('width', poster.attr('width'));
          flowplayer($(link).attr('id')+'_wrapper', '/flowplayer-3.2.2.swf', vid.attr('href')).play();
    }
};
$(window).load(function(){
    // we need to figure out if the method of video inclusion
    $('.video').click(function() {
          play_video($(this));
          if(method!='do-nothing') {
		return false;
          }
    });
    $('a.video').each(function() {
	if($(this).parent('p').hasClass('media-container')) {
		$(this).parent('p').css('height', $('img', $(this)).attr('height'));
	}
    });
    $('.nav a.textlink').hover(function() {
		img = $('img', $(this));
		img.attr('src', img.attr('src').replace('/img/','/img/hovered/'));
                $(this).css('color', '#0078FF');
	}, function() {
		img = $('img', $(this));
		img.attr('src', img.attr('src').replace('/img/hovered/','/img/'));
                $(this).css('color', '#FFFFFF');
	});
$.get('/img/hovered/nav-chums.png');
$.get('/img/hovered/nav-drop-a-line.png');
$.get('/img/hovered/nav-food-chain.png');
$.get('/img/hovered/nav-sightings.png');
$.get('/img/hovered/nav-vitals.png');

});

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11846558-1']);
var load_tracked = false;
$(function(){
  // 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).bind( 'hashchange', function(){
    var hash = location.hash;
    var url = hash.replace(/^#/,'partial');
    if(url!=hash) {
        load_tracked = true;
if(url == 'partial/index') {
		$('body').addClass('page-index');
   	    } else {
	      	$('body').removeClass('page-index');
            }
        $('.content').fadeOut('fast', function() {
	    $.get(url, function(data) {
                $('.content').html(data);
                $('.content').fadeIn('slow');
                $('.video').click(function() {
                    play_video($(this));
                    if(method!='do-nothing') {
                        return false;
                    }
                });
                if(!$('.video:first').hasClass('noautoplay')) {
                      if(method!='html5') {
	                      play_video($('.video:first'));
                      }
                }
                $('a').each(function() { 
                      if(!$(this).hasClass('video') && !$(this).hasClass('image') && !$(this).attr('href').match(/^http/)) {
			$(this).attr('href', '#' + $(this).attr('href').replace(/^#/, '')); 
		      } else if($(this).parent('p').hasClass('media-container')) {
			$(this).parent('p').css('height', $('img', $(this)).attr('height'));
                      }
                });
                tb_init('a.thickbox');
		$('#twitter').getTwitter({userName: "zambezi_la"});
		try {
		  var project_title = $('.content .project-client:first').text()+': '+$('.content .project-title:first').text();
		  if(project_title != ': ') {
			  _gaq.push(['_setCustomVar', 1, 'project', project_title, 3]);
                  } else {
			  _gaq.push(['_setCustomVar', 1, 'project', 'n/a - other page', 3]);
		  }
		} catch(err) {}
		try {
		  _gaq.push(['_trackPageview', url.replace(/^partial/,'')]);
		} catch(err) {}
            });
        });
    }
  });

// IE 8 works IE 7 does not
if(!( $.browser.msie && $.browser.version < 8)) {
  // convert all links to hashtags
  $(window).load(function() {
    $('a').each(function() {
      if(!$(this).hasClass('video') && !$(this).hasClass('image') && !$(this).attr('href').match(/^http/) ) {
        $(this).attr('href', '#' + $(this).attr('href').replace(/^#/, ''));
      }
    });
    $('.wrapper').css('minHeight', ( $(window).height() + 10 ));
  });
  // 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.
  if(location.hash!='#/index' && location.hash!='') {
     $('.content').hide();
     $(window).trigger( 'hashchange' );
  }
}



if(load_tracked == false) {
	_gaq.push(['_trackPageview']);
}

});


function twitterCallbackZ(twitters) {
  var nodes = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a class="tweetlink" href="'+url+'">'+url+'</a>';
    }).replace(/\B(@[_a-z0-9]+)/ig, function(reply) {
      return  '<a class="tweetlink" href="http://twitter.com/'+reply.substring(1)+'">'+reply+'</a>';
    }).replace(/\B(#[_a-z0-9]+)/ig, function(hashtag) {
      return  '<a class="tweetlink" href="http://twitter.com/search?q=%23'+hashtag.substring(1)+'">'+hashtag+'</a>';
    });
    node = $('<li></li>').html('<span class="tweetcontent">'+status+'</span> <span class="tweetmeta"><a class="tweetlink" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id_str+'">'+relative_time(twitters[i].created_at)+'</a></span>');
    nodes.push(node);
  }
  list = $('#twitter_update_list');
  for ( var i=0; i<nodes.length; i++) {
    list.append(nodes[i]);
  }
  maxheight = ( parseInt($('#twitter').height()) - parseInt($('.twitterheader').height()));

  while(parseInt(list.height()) > maxheight ) {
     $('li:last', list).remove();
  }
}

/* from http://twitter.com/javascripts/blogger.js */
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

(function($) {
	$.fn.getTwitter = function(options) {

		$.fn.getTwitter.defaults = {
			numTweets: 30
		};

		var o = $.extend({}, $.fn.getTwitter.defaults, options);

		return this.each(function() {
			var tl = $("#twitter_update_list");
			$.getScript("http://twitter.com/statuses/user_timeline/"+o.userName+".json?callback=twitterCallbackZ&count="+o.numTweets, function() {
				// remove preLoader from container element
				$('#twitterloading').remove();
			});
		});
	};
})(jQuery);

$(document).ready(function() {
	$('#twitter').getTwitter({userName: "zambezi_la"});
        $('body').delegate('.mailactivate', 'click', function() {
            if($('.mailer').is(':visible')) {
             		$('.mailer').slideUp('normal');
            } else {
		            $('.mailer').slideDown('normal', function() {
                        $('.mailbody').focus();
		            });
            }
        });
	$.get('/img/submit-button-hovered.png');
  $('body').delegate('.subscribeactivate', 'click', function() {
    if($('.subscriber').is(':visible')) {
   		$('.subscriber').slideUp('normal');
    } else {
	    $('.subscriber').slideDown('normal', function() {
	      $('.subscribefrom').focus().select();
	    });
    }
  });
	$('body').delegate('.subscribeactivate img', 'mouseenter mouseout', function() {
    if($(this).parents('.subscribeactivate:first').hasClass('responded')) {
      // ignore the hover, we want to keep the message
    } else {
      if(event.type == 'mouseover') {
        $(this).attr('src', '/img/subscribe-to-our-bites-newsletter-hovered.png');
      } else {
        $(this).attr('src', '/img/subscribe-to-our-bites-newsletter.png');
      }
    }
	});
	$.get('/img/subscribe-to-our-bites-newsletter-hovered.png');
	$('body').delegate('.subscriber', 'submit', function() {
    $('.submit-image').attr('src', '/img/submit-button-hovered.png');
		$.post('/subscribe.php', $('.subscriber').serialize(), function(data) {
			$('.subscriber').slideUp('fast', function() {
        $('.subscribeactivate').addClass('responded').html(data);
        $('.submit-image').attr('src', '/img/submit-button.png');
			});
		});
		return false;
	});
});



(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

