document.write('<script type="text/javascript" src="http://instablogs.com/api/js/jquery.js"></script>');
document.write('<script type="text/javascript" src="http://instablogs.com/api/js/jquery-dom.js"></script>');
document.write('<link rel="stylesheet" type="text/css" media="all" href="http://www.instablogs.com/insta_widgets/css/insta-club-widget.css" />');

club_id = typeof club_id  == 'string' ? ''+club_id+''  : 'insta-club-container';

document.write('<div id="show_club_posts"></div>');
document.write('<div id="'+club_id+'">');
document.write('<ul></ul></div>');

function substr( f_string, f_start, f_length ) {
    f_string += '';
 
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}

function insta_club(obj)
{
	$j('#'+club_id+' ul').html('');
	var tpl1 = function()
	{
		var image_path = 'http://www.instablogsimages.com/';

		var first_image_name=this.first_image_name;
		if(first_image_name != '')
		{
			var image_extension=substr(first_image_name, -4);
			var replace_text="_75x65" + image_extension;
			var small_image = first_image_name.replace(image_extension, replace_text);

			return [
				'li', {'class':'single-story'},
						[
							'div', {'class':'club-story'},
							[
								'a', { 'href': this.ext_perma_url},
								[
									'img', {'src': image_path + small_image}
								]
							],
							'div', {'class':'story-title'}, 
							[
								'a', { 'href': this.ext_perma_url}, this.title
							],
							'div', {'class':'story-blog'}, 
							[
								'a', { 'href': this.blog_url}, this.blog_name
							]
						]
					];
		}
		else
		{
			return [
				'li', {'class':'single-story'},
						[
							'div', {'class':'story-title'}, 
							[
								'a', { 'href': this.ext_perma_url}, this.title
							],
							'div', {'class':'story-blog'}, 
							[
								'a', { 'href': this.blog_url}, this.blog_name
							]
						]
					];

		}
	};

	if(!obj)
	{
		$j('#'+club_id+' ul').html('We were unable to retrieve matching stories from insta. Please refresh the page to try again.');
	}

	if(!obj.Story || obj.Story.length == 0) 
	{
		$j('#'+club_id+' ul').html('Currently, there are no recent stories of this type on insta.');
	}

	for (var i = 0 ; i < obj.Story.length ; i++) 
	{
		$j('#'+club_id+' ul').tplAppend(obj.Story[i], tpl1);
	}
}
