var numFeedsReady = 0;
var numFeeds = 4;
var youtube_primary_svc_url		= "/svc/getYouTubeVideos.php?user=IamCPS";
var twitter_svc_url				= "http://search.twitter.com/search.json?q=from%3aIamCPS&rpp=1&page=1&callback=?"; //"/svc/getTwitterUpdates.php?user=IamCPS";
var picasa_svc_url				= "/svc/getPicasaPhotos.php?user=Iamcps.k12&limit=3";
var blog_svc_url				= "/svc/getBlogPosts.php?feed=http://iamcps.typepad.com/iamcps/atom.xml";
var IE6;
var isIE = false;

// Big Background Images
var bgArray = ['football', 'readers', 'testers', 'chemistry', 'computerkids'];
var bgArrayCnt = bgArray.length;

// Globally accessible variables
var youtubeVideos;
var playerReady = false;
var youtubeDataReady = false;

$(document).ready(function(){
    // AJAX calls for aggregator
    $.get(youtube_primary_svc_url, null, onYouTubePrimary, "json");
    $.getJSON(twitter_svc_url, onTwitter); //null, onTwitter, "json");
    $.get(picasa_svc_url, null, onPicasa, "json");
    $.get(blog_svc_url, null, onBlogFeed, "json");

    // only utilize if browser is IE6
    IE6 = (navigator.appVersion.indexOf("MSIE 6") > 0) ? true : false;
	if (navigator.userAgent.indexOf("MSIE") > -1) isIE = true;
	
    if(IE6)
    {
        $('#submit-story').hover(
            function(){
                $(this).css('background-image', 'none');
            },

            function(){
                $(this).removeClass('on');
            }
        );
    }
});

/**
 * Change ID attribute of Body tag.
 *
 * By locating the current background id
 * we can determine whether to move to the next
 * id or start with the first
 */
function changeBackground()
{
    var curBg = $('body').attr('id');
    var load = '';

    for(var i = 0; i < bgArrayCnt; i++)
    {
        // if the pointers value matches the curbg,
        // load the next id and then break out of loop
        if(bgArray[i] == curBg)
        {
            load = ((i + 1) == bgArrayCnt) ? 0 : i + 1;

            $('body').attr({id: bgArray[load]});

            break;
        }
    }
}

function attachGAClickTags()
{
	var links = document.getElementsByTagName("a");
	var linkCount = links.length;
	for (var linkIndex = 0; linkIndex < linkCount; linkIndex++)
	{
		var lnk = links[linkIndex];
		if (isIE)
		{
			lnk.attachEvent("onclick", function(e){
				var title = e.srcElement.title;
				_gaq.push(['_trackEvent', 'External Link Click Actions', 'Click', title]);
				//pageTracker._trackEvent("External Link Click Actions", "Click", title);
			});
		}
		else
		{
			lnk.addEventListener("click", function(e){
				var title = e.target.title;
				_gaq.push(['_trackEvent', 'External Link Click Actions', 'Click', title]);
				//pageTracker._trackEvent("External Link Click Actions", "Click", title);
			}, false);
		}
	}
}

// ------------------------------------------------------------------

/**
 *  Update the height of the translucent background.  Considering
 *  several data blocks will not have been fully loaded, it is
 *  important to call this at the end of every callback function.
 */
function updateTranslucentHeight()
{
    $('#full-translucent').css({height: $("#content-wrapper").height() + 30});
}

// ------------------------------------------------------------------

function onYouTubePrimary(data)
{
    max = 6;
	var user	= data["user"];
	var videos	= data["videos"];
	youtubeVideos = videos;
	var container = $("#videos-display .hdr");
	var append = [];
    var video = '';
    var pre = '';
    var suf = '';

	for (var videoIndex = 0; videoIndex < max; videoIndex++)
	{
		video = videos[videoIndex];
        pre = (videoIndex == 0 || videoIndex == 3) ? "<ul class='clearfix'>\r\n" : '';
        suf = (videoIndex == 2 || ((videoIndex + 1) == max)) ? "</ul>\r\n" : '';

        if(typeof(video) != 'undefined')
        {
            var title = video['title'];
            var thumbnail = video['thumbnail'];
            var description = video['description'];
            var id = video['id'];
			var url = video["url"];

            muThumb = "<span class='thb-holder'><img src='" + thumbnail + "' alt='" + cleanCharacters(title) + "' title='" + cleanCharacters(description) + "' /></span>";
            muAnchor = "<a href='javascript:void(0);' onclick=\"cueNewVideo('" + id + "', '" + cleanCharacters(title) + "', '" + cleanCharacters(description) + "', '" + url + "');\" title=\"YouTube: " + cleanCharacters(title) + "\">" + title + "</a>";
        }
        else
        {
            muThumb = "<span class='thb-holder'><!-- --></span>";
            muAnchor = "";
        }

		append.push(pre + "<li>" + muThumb + muAnchor + "</li>\r\n" + suf);
	}

	$(container).after(append.join(""));
    updateTranslucentHeight();
	
	cueNewVideo(videos[0]["id"], cleanCharacters(videos[0]["title"]), cleanCharacters(videos[0]["description"]), videos[0]["url"]);
	
	incrementFeedsReady();
}

function cleanCharacters(string)
{
	string = string.replace(/\"/g, "");
	string = string.replace(/'/g, "");
	string = string.split("&#039;").join("");
	string = string.split("\n").join("<br />");
	return string;
}

function incrementFeedsReady()
{
	numFeedsReady++;
	if (numFeedsReady == numFeeds)
	{
		attachGAClickTags();
	}
}

function cueNewVideo(id, title, description, url)
{
	var params = {allowScriptAccess: "always", bgcolor: "#cccccc", wmode:"transparent"};
	var isIE6 = navigator.userAgent.indexOf("MSIE 6") > -1;
	
	if (isIE6 == true)
	{
		$("#youtube_player").html(createFullFlash("http://www.youtube.com/v/" + id, 460, 344));
	}
	else
	{
		swfobject.embedSWF("http://www.youtube.com/v/" + id + "&hl=en&rel=0", "youtube_player", "460", "344", "8", null, null, params, null);
	}
	
	var html = "<a href=\"" + url + "\" target=\"_blank\" title=\"" + title + "\" onclick=\"_gaq.push(['_trackEvent', 'External Link Click Actions', 'Click', this.title]);\">" + title + "</a>";
	$("#video-title").html(html);
	$("#video-description").html(description);
	
}

function createFullFlash(path, theWidth, theHeight)
{
	var string = "";
	string += "<object width=\"" + theWidth + "\" height=\"" + theHeight + "\">";
	string += "<param name=\"movie\" value=\"" + path + "\"></param>";
	string += "<param name=\"allowFullScreen\" value=\"true\"></param>";
	string += "<param name=\"allowscriptaccess\" value=\"always\"></param>";
	string += "<param name=\"wmode\" value=\"transparent\"></param>";
	string += "<embed wmode=\"transparent\" src=\"" + path + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" + theWidth + "\" height=\"" + theHeight + "\"></embed>";
	string += "</object>";

	return string;
}

// ------------------------------------------------------------------

/**
 * Ajax Callback function
 *
 * This function assembles the returned Twitter data
 * into several tweets (upto max).
 */
function onTwitter(data)
{
	data = data["results"];
    var max = 1;
	if (data.length < max) max = data.length;
	var container = $("#twitter .clear");
	var append = [];
    var status;

    // traverse through tweets, by stopping at max we confirm
    // that only the latest tweets will be displayed
	for (var statusIndex = 0; statusIndex < max; statusIndex++)
	{
        status = data[statusIndex];
		var statusID	= status["id"];
		var statusText	= status["text"];
		//var statusDate	= status["created_at"];

        var muTweet = "<p class='tweet'><a href='http://twitter.com/iamcps/statuses/" + statusID + "' target='_blank' title='Twitter: " + statusText + "'>" + statusText + "</a></p>";
        var muTweetDate = '';//"<p class='tweet-date'>" + humane_date(statusDate) + "</p>";

		append.push("<div class='post-item'>" + muTweet + "\r\n" + muTweetDate + "</div>\r\n");
	}
	
	$(container).after(append.join(""));
    updateTranslucentHeight();
	
	incrementFeedsReady();
}

// ------------------------------------------------------------------

function onPicasa(data)
{
	var container = $("#photos .hdr");
	//var user		= data["user"];
	//var userPage	= data["page"];
	//var avatar		= data["avatar"];
	var photos		= data["albums"]; //["photos"];
	var photoCount	= photos.length;
	var append = [];
	
	for (var photoIndex = 0; photoIndex < photoCount; photoIndex++)
	{
		var photo		= photos[photoIndex];
		var title		= photo["title"];
		var photoDate   = photo["date"];
		var thumbnail	= photo["thumbnail"];
		var photoPage	= photo["page"];

        var muImg = "<a href='" + photoPage + "' target='_blank'><img width=\"72\" src='" + thumbnail + "' title='Picasa: " + cleanCharacters(title) + "' alt='' /></a>";
        var muImgTitle = "<p class='img-title'><a href='" + photoPage + "' target='_blank' title='Picasa: " + cleanCharacters(title) + "'>" + title + "</a></p>";
        var muImgDate = '';//"<p class='img-post-date'>posted on " + humane_date(photoDate) + "</p>";

		append.push("<div class='post-item'>" + muImg + "\r\n" + muImgTitle + "\r\n" + muImgDate + "</div>\r\n");
	}
	
	$(container).after(append.join(""));
    updateTranslucentHeight();
	
	incrementFeedsReady();
}

// ------------------------------------------------------------------

function onBlogFeed(data)
{
    var max = 3;
	var descriptionMax = 192;
	var container = $("#blog-posts a");
	var append = [];
    var post = '';
	
	for (var postIndex = 0; postIndex < max; postIndex++)
	{
		post		= data[postIndex];

		var title		= post["title"];
		var permalink	= post["link"];
		var postDate	= post["date"];
		var author		= post["author"];
        var summary		= post["summary"];
		var description = summary.substr(0, descriptionMax);
		if (summary.length > descriptionMax) description += " [...]"
		
        var muDate = '';//"<p class='date'>" + humane_date(postDate) + "</p>";
        var muTitle = "<h3><a href='" + permalink + "' target='_blank' title='Blog: " + cleanCharacters(title) + "'>" + title + "</a></h3>";
        var muDescription = "<p>" + description + "<span class='split'>---</span><span class='more'><a href='" + permalink + "' target='_blank' title='Blog: " + cleanCharacters(title) + "'>More...</a></span></p>";

		append.push("<div class='post-item'>" + muDate + "\r\n" + muTitle + "\r\n" + muDescription + "</div>\r\n");
	}

	$(container).after(append.join(""));
    updateTranslucentHeight();
	
	incrementFeedsReady();
}

function popNewsletter()
{
	var newsletterWindow = new NewWindow(
		{id: "form_newsletter", closeButton: ["form_newsletter_close"]}								
	);
	newsletterWindow.open();
	document.getElementById("newsletter_fname").focus();
}

function popNewsletterThankYou()
{
	var newsletterWindow = new NewWindow(
		{id: "thankyou_newsletter", closeButton: ["thankyou_close"]}								
	);
	newsletterWindow.open();
}

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 *
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 *
 * Licensed under the MIT license.
 */
function humane_date(date_str){
	var time_formats = [
		[60, 'Just Now'],
		[90, '1 Minute'], // 60*1.5
		[3600, 'Minutes', 60], // 60*60, 60
		[5400, '1 Hour'], // 60*60*1.5
		[86400, 'Hours', 3600], // 60*60*24, 60*60
		[129600, '1 Day'], // 60*60*24*1.5
		[604800, 'Days', 86400], // 60*60*24*7, 60*60*24
		[907200, '1 Week'], // 60*60*24*7*1.5
		[2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
		[3942000, '1 Month'], // 60*60*24*(365/12)*1.5
		[31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
		[47304000, '1 Year'], // 60*60*24*365*1.5
		[3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
		[4730400000, '1 Century'], // 60*60*24*365*100*1.5
	];

	var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
		dt = new Date,
		seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
		token = ' Ago',
		i = 0,
		format;

	if (seconds < 0) {
		seconds = Math.abs(seconds);
		token = '';
	}

	while (format = time_formats[i++]) {
		if (seconds < format[0]) {
			if (format.length == 2) {
				return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
			} else {
				return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
			}
		}
	}

	// overflow for centuries
	if(seconds > 4730400000)
		return Math.round(seconds / 4730400000) + ' Centuries' + token;

	return date_str;
};

