/**
 * Javascripts for the 2009 redesign by Singularity Media
 * 
 * @author Josh Mahoney
 */



/**
 * Runs the startup functions onload
 */
function RunScripts()
{	
	
	//catch any errors when doing AJAX requests
	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;
			document.getElementById('latestblogdesc').innerHTML=msg;

			// Unhiding this makes it a hell of a lot easier to 
			// troubleshoot when your AJAX is playing up
			/*
			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('Internal 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 blog feed and when it returns, parse it
	jQuery.getFeed({
		url: 'http://heywire.abc.net.au/service/getHttpUrl.kickAction?urlLink=http://blogs.abc.net.au/heywire/rss.xml',
		success: function(rssxml){
			
			//clear the loading graphics
			document.getElementById('latestblogdesc').innerHTML="";
			document.getElementById('footerbloglist').innerHTML="";
			document.getElementById('blogcontent').innerHTML="";
			
			//add the blog articles in the RSS feed to the various places
			jQuery.each(rssxml.items, function(i, n){
				if ($('ka_homepage')&&i == 0) {
					var htmlcontent2 = '<div class="entry"><div class="blogtitle"><a href="' + n.link + '">' + n.title + '</a></div><div class="blogcontent">' + n.description + '<div id="readmorelink"><a href="' + n.link + '">Keep reading more on the Heywire Blog</a></div></div></div>';
					document.getElementById('latestblogdesc').innerHTML += htmlcontent2;
				}
				else {
					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://heywire.abc.net.au/service/getHttpUrl.kickAction?urlLink=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://heywire.abc.net.au/service/getHttpUrl.kickAction?urlLink=http://blogs.abc.net.au/heywire/featured.html',
        dataType: "text",
        success: function(data) {
			document.getElementById("featblogcontent").innerHTML=data;
        }
    });
	
	// move the kickapps elements to the right places
	moveMenu();
	moveLogin();
	moveTagCloud();
	moveSearch();

	// do the javascript moving and hiding for the homepage
	if ($('ka_mainContainer').className.search("ka_homePage")!=-1) {
		moveVideo();
		moveLatestBlog();
		moveMapGFX();
		$('ka_headerSubNav').style.display="none";
	}else
	{
		$('latestblogbox').style.display="none";
	}


	//flag for blog page
	var isBlogPage=false;

	// shuffle the bits around if it's a blog page	
	if ($('ka_mainContainer').className.search("ka_mediaPlayPage ka_blogPlayPage") != -1) {
		
		isBlogPage=true;
		

		if($('ka_adminControl'))
		{
			prependChild($('ka_descriptionBlog'),$('ka_adminControl'));
		}
		prependChild($('ka_descriptionBlog'),$('ka_playPageDetails'));
		
		
		insertAfter($('ka_mainContainer'),$('ka_leftColumn'),$('ka_contentContainer'));
		insertAfter($('ka_mainContainer'),$('ka_rightColumn'),$('ka_contentContainer'));
		
		$('ka_contentContainer').appendChild($('ka_playPagePlayer_blog'));
		
		var clearDiv = document.createElement('div');
		clearDiv.setAttribute('class', 'clearDiv');
		$('ka_mainContainer').appendChild(clearDiv);
		
		
	}

	
	//if logged in show/hide the appropriate bits
	if (isLoggedIn()) {
		$('login').style.display = "none";
		$('loggedin').style.display = "block";
	}
	else {
		$('login').style.display = "block";
		$('loggedin').style.display = "none";
		$('ka_myhomeTab').style.display = "none";
	}
	
	$('loginfooter').style.display = "none";
	$('loggedinfooter').style.display = "block";

	
	//if it's a play page (but not a blog page) move the comments to the bottom of the page
	if($('ka_playPage')&&!isBlogPage)
	{
		if ($('ka_shoutBoxContainer')) {
			$('ka_contentContainer').insertBefore($('ka_shoutBoxContainer'), null);
			if ($('ka_commentLog')) 
				$('ka_leftColumn').insertBefore($('ka_commentLog'),null);
		}
	}
	
	//if it's a play page and a photo page, move the photo up
	if ($('ka_playPage') && $('ka_playPage').className.search("photo") != -1) {
		if($('ka_playPagePlayer'))
		{
			$('ka_contentContainer').insertBefore($('ka_playPagePlayer'),$('ka_leftColumn'));
		}
	}

	
	// raise the curtain
	showEverything();
}


/* Handy DOM functions 
 * 
 * Dethe Elza
 * http://www.ibm.com/developerworks/xml/library/x-matters41.html
 */
function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}
function prependChild(parent, node) {
    parent.insertBefore(node, parent.firstChild);
}



/**
 * Moves the default kickapps menu to inside the 'newMenu' div
 */
function moveMenu()
{
	if($('newMenu')&&$('ka_header'))
		$('newMenu').appendChild($('ka_header'));
}

/**
 * Moves the default Kickapps login links/form into the 'newLogin' div
 */
function moveLogin()
{
	if($('newLogin')&&$('ka_headerLogin'))
		$('newLogin').appendChild($('ka_headerLogin'));
}

/**
 * Moves the tag cloud into the 'newTag' div
 */
function moveTagCloud()
{
	if($('tagCloud')&&$('ka_tagModule'))
		$('tagCloud').appendChild($('ka_tagModule'));
	else
	{
		$('tagHolder').style.display="none";
	}

}

/**
 * Moves the video player to the newVideo div
 */
function moveVideo()
{
	if($('ka_leftColumn')&&$('ka_videoPlayer'))
		$('ka_leftColumn').insertBefore($('ka_videoPlayer'),$('ka_leftColumn').firstChild)
}

/**
 * Moves the latest blog widget (and unhides)
 */
function moveLatestBlog()
{
	if ($('ka_leftColumn') && $('latestblogbox')) {
		$('ka_leftColumn').insertBefore($('latestblogbox'), $('ka_leftColumn').firstChild)
		$('latestblogbox').style.display = "block";
	}
}


/**
 * Moves the map gfx
 */
function moveMapGFX(){
	if ($('ka_leftColumn') && $('mapgfx')) {
		$('ka_leftColumn').insertBefore($('mapgfx'), $('ka_leftColumn').firstChild)
		$('mapgfx').style.display = "block";
	}
}


/**
 * Moves the search box
 */
function moveSearch()
{
	if ($('ka_headerSearch') && $('searchbox') && $('searchtitle')) {
		$('searchbox').appendChild($('ka_headerSearch'));
		$('ka_headerSearch').style.display = "block";
		
		document.ka_search.keywords.value = "Enter search keywords...";
		
		document.ka_search.keywords.onclick=function(){
			document.ka_search.keywords.value="";
		};
	}
	
}

/**
 * Unhides all the pages content
 * And hides the loading icon
 */
function showEverything()
{
	$('container-inner').style.display="block";
	$('loading').style.display="none";
}

function showMap()
{
	var maploc="http://maps.google.com.au/maps/ms?ie=UTF8&amp;oe=UTF8&amp;msa=0&amp;msid=104288761948945844159.00047820012748af3ec4c&amp;ll=-28.075164,134.447593&amp;spn=29.456597,37.506637&amp;output=embed";
	var iframecontent='<iframe id="googmap" width="700" height="500" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+maploc+'"></iframe>';
	document.getElementById("googmapholder").innerHTML=iframecontent;
	$('mapholder').style.display='block'; 
	jQuery('mapholder').find("iframe").attr("src",maploc);
	return false;
}


function fixThumbNails()
{
	jQuery.find('.ka_searchLetterBox').css("background-color","red");
}


/**
 * Returns true if a kickapps user is logged in
 */
function isLoggedIn()
{
	
	if (Ka.Info.USERID == '') {
		return false;
	}
	else {
		return true;
	}
}

					
/* 
 * 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;
}


//add all the javascript bits we need to do to the Kickapps onload
Ka.addDOMLoadEvent(addTab);
Ka.addDOMLoadEvent(editTopNavLinks);
Ka.addDOMLoadEvent(rebuildEditAccount);
Ka.addDOMLoadEvent(RunScripts);
