/**
 * Javascripts for the 2009 redesign by Singularity Media
 * These scripts are used by the Typepad blog only.
 * 
 * @author Josh Mahoney
 */



/**
 * Runs the startup functions onload
 */
function RunScripts()
{	
	

	jQuery.ajaxSetup({
		error:function(x,e){
			var msg='<b>Opps! Error reading latest blog content</b><br/>Visit the <a href="http://blogs.abc.net.au/heywire/">Heywire Blog</a> for articles<br/>and news from the Heywire team';
			document.getElementById('blogcontent').innerHTML=msg;
			document.getElementById('footerbloglist').innerHTML=msg;

			/*
			if(x.status==0){
			alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
			alert('Requested URL not found.');
			}else if(x.status==500){
			alert('Internel Server Error.');
			}else if(e=='parsererror'){
			alert('Error.\nParsing JSON Request failed.\n'+x.responseText);
			}else if(e=='timeout'){
			alert('Request Time out.');
			}else {
			alert('Unknow Error.\n'+x.responseText);
			} 
			*/

		}
	});



	
	//request the feed and when it returns, parse it
	jQuery.getFeed({
		url: 'http://blogs.abc.net.au/heywire/rss.xml',
		success: function(rssxml){
			
			//clear the loading graphics
			document.getElementById('footerbloglist').innerHTML="";
			document.getElementById('blogcontent').innerHTML="";
			
			jQuery.each(rssxml.items, function(i, n){

					if (i < 4) {
						var lastclass = "";
						if (i == 3) {
							lastclass = " last";
						}
						var htmlcontent = '<div class="entry ' + lastclass + '"><div class="blogtitle"><a href="' + n.link + '">' + n.title + '</a></div><div class="blogcontent">' + n.description.substring(0, 100) + '...</div></div>';
						document.getElementById('blogcontent').innerHTML += htmlcontent;
					}

				
				var htmlcontent = '<li><a href="' + n.link + '" title="' + n.title + '">' + n.title.substring(0, 60) + '...</a></li>';
				document.getElementById('footerbloglist').innerHTML += htmlcontent;
				
			});
		}
	});


	/* Get the blogs most recent comments and update */
    jQuery.ajax({
        type: 'GET',
        url: 'http://blogs.abc.net.au/heywire/recentcomments.html',
        dataType: "text",
        success: function(data) {
			document.getElementById("blogcomments").innerHTML=data;
        }
    });
	
	/* Get the blogs featured article and update */
    jQuery.ajax({
        type: 'GET',
        url: 'http://blogs.abc.net.au/heywire/featured.html',
        dataType: "text",
        success: function(data) {
			   if(document.getElementById("featblogcontent")!=null)
				  document.getElementById("featblogcontent").innerHTML=data;
        }
    });


	if (isLoggedIn()) {
		$('login').style.display = "none";
		$('loggedin').style.display = "block";
		$('loginfooter').style.display = "none";
		$('loggedinfooter').style.display = "block";
	}
	else {
		$('login').style.display = "block";
		$('loggedin').style.display = "none";
		$('loginfooter').style.display = "block";
		$('loggedinfooter').style.display = "none";
	}
	
	//HIDE THE LOGIN BOX ON THE BLOG
	$('login').style.display = "none";
	$('loginfooter').style.display = "none";

}



					
/* 
 * Linkify from:
 * 
 * http://snipplr.com/view.php?codeview&id=13533
 * 
 * Adapted to include @... twitter links
 * 
 */
function linkify(text)
{
	var atregular = /\B@([_a-z0-9]+)/ig;

	if( !text ) return text;
	
	text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
		nice = url;
		if( url.match('^https?:\/\/') )
		{
			nice = nice.replace(/^https?:\/\//i,'')
		}
		else
			url = 'http://'+url;
		
		
		
		return '<a target="_blank" rel="nofollow" href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>';
	});
	
	text = text.replace(atregular, '@<a href="http://twitter.com/$1">$1</a>');
	
	return text;
}
	
	
/* 
 * Twitter search adapted from:
 * 
 * Rob Larsen / DrunkenFist.com
 * http://www.drunkenfist.com/304/2008/10/30/twitter-search-results-with-json-and-callbacks/
 * 
 */
	
function twitterSearch(obj) {	
    //this is the div I'm writing the content to	
    var tDiv = document.getElementById("tweetbox");	
    var user, bgcolor, tweet, postedAt, icon, userURL;	
	var datePosted;
    //start the ul	
    tDiv.innerHTML = "<ul>"	
    for (i=0;i<obj.results.length;i++) {	
	
        //we need to get some data out of the object
        //and populate some variables.
        //i could do this inline in the string below, 
        //but this is way easier for you to read
        icon = obj.results[i].profile_image_url;
        user = obj.results[i].from_user;
        userURL = "http://twitter.com/"+user;
		
        tweet = linkify(obj.results[i].text);
		
		datePosted = new Date();
		datePosted.setTime(Date.parse(obj.results[i].created_at));
		postedAt = datePosted.toLocaleTimeString() +" on "+datePosted.toDateString();
	    //and here I mash it all up into a fancy li
		tDiv.innerHTML+="<li><div class='a_tweet'><a href='"+userURL+"'><img src='"+icon+"' class='tweetico'/></a>"+tweet+"<div class='time'>"+postedAt+" from <a href='"+userURL+"'>"+user+"</a></div></div></li>";

	}	
    //and close the UL
    tDiv.innerHTML += "</ul>";
}
//this is basically the same function I was using before
//with the changed search URL
function twitter() { 
    var twitterJSON = document.createElement("script"); 
    twitterJSON.type="text/javascript" 
    //here's the search URL
    twitterJSON.src="http://search.twitter.com/search.json?callback=twitterSearch&q=@heywire&rpp=7"
    document.getElementsByTagName("head")[0].appendChild(twitterJSON);
    return false;
}



/**
 * Returns true if a kickapps user is logged in
 */
function isLoggedIn()
{
	if (typeof(Ka) == 'undefined') {
		return false;
	}
	else {
		if (Ka.Info.USERID == '') {
			return false;
		}
		else {
			return true;
		}
	}
}

window.onload=RunScripts;
