// basic jQuery extensions
$.extend($,
{
	// for debugging purposes - caution - writes to global space
	log : function()
	{
		window.log = function(){
			try{
				console.log.apply(console,arguments);
			} catch(error)
			{
				// .. IE
			}
		};
		return window.log;
	}(),
	
	// Original Author: Rafael Lima (http://rafael.adm.br)
	cssBrowserSelect : (function()
	{
		var ua=navigator.userAgent.toLowerCase(),
			is=function(t){ return ua.indexOf(t) != -1; },
			h=document.getElementsByTagName('html')[0],
			b=( !(/opera|webtv/i.test(ua)) && /msie (\d)/.test(ua) )? ('ie ie'+RegExp.$1):
				is('gecko/')? 'gecko':
					is('opera/9')? 'opera opera9':
						/opera (\d)/.test(ua)? 'opera opera'+RegExp.$1:
							is('konqueror')? 'konqueror':
								is('applewebkit/')? 'webkit safari':
									is('mozilla/')? 'gecko':'',
			os=( is('x11')||is('linux') )? ' linux':
				is('mac')? ' mac':
					is('win')? ' win':
						'',
			c=b+os+' js';
		
		h.className += h.className?' '+c:c;
		
		return true;
	})()
});

/*
Title:      jQuery.relativeDate
Description:Formats a date relative to current time (eg '3 mins ago')
Developer:  Antenna Praxis (http://the-antenna.org)
Date:       May 2009
Version:    0.1
Usage:      
Notes:      
To Do:      
License:    Dual licensed under the MIT and GPL licenses:
            http://www.opensource.org/licenses/mit-license.php,
            http://www.gnu.org/licenses/gpl.html
*/

(function($) {
	
	var a_minute = 60 *1000,
		an_hour = a_minute*60,
		a_day = an_hour*24,
		a_month = a_day*30, // averaged
		a_year = a_day*365,
		years,months,days,hours,minutes,secs,
		_plural = "s",
		_seperator = " ",
		_now = new Date();
	
	$.relativeDate = function(date, now)
	{
		//years = months = days = hours = minutes = secs = 0;
		
		if(typeof date == "string") date = new Date(date);
		secs = (now || _now).getTime() - date.getTime();
	
		years = Math.floor(secs/a_year);
		secs = secs%a_year;
		months = Math.floor(secs/a_month);
		
		secs = secs%a_month;
		days = Math.floor(secs/a_day);
		secs = secs%a_day;
		hours = Math.floor(secs/an_hour);
		secs = secs%an_hour;
		minutes = Math.floor(secs/a_minute);
		
		return formattedDate();
	};
	
	formattedDate = function()
	{
		if(years > 0) return displayDate(years,' year');
		else if(months > 0) return displayDate(months + (days>15? 1 : 0),' month');
		else if(days > 0) return displayDate(days + (hours>12? 1 : 0),' day');
		else if(hours > 0) return displayDate(hours + (minutes>30? 1 : 0),' hour') ;
		else return displayDate(minutes ,' minute');
	}
	
	displayDate = function(num, string, seperator, plural)
	{
		plural = plural || _plural,
		seperator = seperator || _seperator;
		return (num? (num!=1? num+string+plural+seperator : num+string+seperator) : "");
	}
	
	
})(jQuery);




// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();


/*
Title:      jquery.inlineLoader
Description:fetches a page and loads data into target via a template, then reveal anim
Developer:  Antenna Praxis (http://the-antenna.org)
Date:       Jun 2009
Version:    0.1
Usage:      
Notes:      
To Do:      
License:    Dual licensed under the MIT and GPL licenses:
            http://www.opensource.org/licenses/mit-license.php,
            http://www.gnu.org/licenses/gpl.html
*/

(function($) {
		  
$.inlineLoader = function (selector,target,template,template_data)
{
	$(selector).click(function(e){
		e.preventDefault();
		$(this).blur();
		
		// switch active class
		$(selector).filter('.active').removeClass('active');
		$(this).addClass('active');
		
		var ni = $(target),
			p = ni.parent();
		
		p.height( p.height() ).css('overflow','hidden'); // fix height
		ni.fadeOut('fast',function(e){ $(this).html('<em class="fetching">Fetching...</em>').show(); });
		
		var href = $(this).attr('href');
		$.ajax({
			url: href,
			success: function(html)
			{	
				var data = $(html).find(target),
					oh = p.height(); // original height
				
				// load in new html
				ni.stop().css('visibility','hidden').html(data) //.html( tmpl(template, template_data(data,href) ) );
				
				var img = ni.find('img'),
					loop = 10 * 10 // 10 secs
					cb = function(){
						
						if(img.height()<10 || loop-- == 0) return false;

						cb2();
						
						clearInterval(to);
						return true;
					},
					cb2 = function(){
						
						// find new height 
						var nh = p.css({height:'',overflow:''}).height();
						p.height(oh); // 
						
						// hide newsitem
						ni.css({opacity:1,visibility:''}).hide();
						// resize then fade in
						p.animate(
							{height: nh}, 'fast',
							function(){ ni.fadeIn(); }
						);
					};
				
				if(img.length){
					// timeout check if img.height() > 100
					if(!cb() ) var to = setInterval(cb,100);
				}
				else cb2();
				
			},
			timeout: 10000,
			error: function(XMLHttpRequest, textStatus, errorThrown){
				ni.show().html('There was a problem, please visit the page directly <a href="'+href+'">here</a>.');
				console.log(XMLHttpRequest, textStatus, errorThrown);
			}
		});
		
	})
}

})(jQuery);
