$(document).ready(function(){
	var archives = $.controller.array("blog/blog_entries", {order: "modified_at DESC"});
	var month_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var last;
	
	$(".archives li").format(function(elem, data){
		var the_date = data.created_at;
		var year = the_date.substr(0, 4);
		var month = the_date.substr(5, 2);
		if (last != year+" "+month) {
 			$(elem).find("h5 a").attr("href","http://www.davehillphoto.com/blog/archives/"+ month +"_"+ year).text(month_names[month - 1] +" "+ year);
 		} else {
 			$(elem).remove();
 		}
 		last = year+" "+month;
		return true;
 	});
 	$(".archives").template(archives);	
	
	var entry = $.controller.array("blog/blog_entries", {include: "blog_entry_comments", limit: 10, order: "created_at DESC", published: "YES"}); 
	$(".date").formatDate("F d, Y  H:iA", "created_at");
	
	$(".entry h3 a").formatLink("{title}", "http://www.davehillphoto.com/blog/{sef_title}");
	$(".entry div.ti_text").format(function(elem, data){
		if(data.auto_br == "YES"){
			var str = data.text;
			str = str.replace(/\n/g, "<br />");
			$(elem).html(str);
		} else {
			$(elem).html(data.text);
		}
		return true;
	});	
	$(".entry .com a").format(function(elem, data){
		$.getJSON("http://www.davehillphoto.com/index.php/api/blog/blog_entry_comments/count?authorized=YES&blog_entry_id=" + data.id, function(data){
			$(elem).find(".com-count").text(data);
		});
		$(elem).attr("href","http://www.davehillphoto.com/blog/" + data.sef_title + "#comments");
		return true;
	});
	
	$(".entry-holder").template(entry, {success: function(){
		$("div.entry div.ti_text img").each(function(){
			$(this).hide();
			var img_src = $(this).attr("src");		
			img_src = img_src.replace(/\{\{\$base_url\}\}/gi, "http://www.davehillphoto.com/");
			$(this).attr("src", img_src).show();
		});
	}});
 
 	var recent = $.controller.array("blog/blog_entries", {limit: 5, order: "modified_at DESC", published: "YES"});
 	$(".recentposts li h5 a").formatLink("{title}", "http://www.davehillphoto.com/blog/{sef_title}");
 	$(".recentposts li p").format(function(elem, data){
        var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;  
        var snip = data.text.replace(regexp,"")  
 		$(elem).html(snip.substring(0, 100)+" ...");
		return true;
 	});
 	
 	$(".recentposts").template(recent);
 	
 	var popular = $.controller.array("blog/blog_entries", {limit: 3, order: "blog_entry_comments_count DESC", published: "YES"});
 	$(".popularposts li h5 a").formatLink("{title}", "http://www.davehillphoto.com/blog/{sef_title}");
 	$(".popularposts li p").format(function(elem, data){
        var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;  
        var snip = data.text.replace(regexp,"")  
 		$(elem).html(snip.substring(0, 100)+" ...");
		return true;
 	});
 	
 	$(".popularposts").template(popular);
});
 
