var feedsRetrieved = 0;
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var chatterArray = new Array();
var chatterIndex = 0;
var chatterCount = 0;
var chatterPages = 0;
var currentChatterPage = 0;
var heightContainerInterval;
var heightContainerIntervalCount = 0;
var imgCount = 0;
var imgsLoaded = 0;

$(function () {
    // twitter feed
    if (twitterName != '') {
        $.ajax({
            url: '/httphandlers/GenericProxy.ashx?url=http://twitter.com/statuses/user_timeline/' + twitterName + '.json',
            dataType: 'json',
            success: function (data) {
                feedsRetrieved++;
                createChatterObjects(data, 'twitter');
            },
            error: function (request, status, errorMsg) {
                alert("error retrieving twitter " + errorMsg);
            }
        });
    }
    if (facebookName != '') {
        // facebook feed
        $.ajax({
            url: '/httphandlers/GenericProxy.ashx?url=http://graph.facebook.com/' + facebookName + '/posts',
            dataType: 'json',
            success: function (data) {
                feedsRetrieved++;
                createChatterObjects(data, 'facebook');
            },
            error: function (request, status, errorMsg) {
                alert("error retrieving facebook " + errorMsg);
            }
        });
    }
});

function updateChatterPagination() {
    $('div.socialFeedContainer span.promoIndex').html(eval(currentChatterPage + 1));
	if (currentChatterPage > 0) {
	    //$('div.socialFeedContainer div.prev').addClass('active');
    } 
    else {
        //$('div.socialFeedContainer div.prev').removeClass('active');
	}
	if (currentChatterPage < chatterPages - 1) {
	    //$('div.socialFeedContainer div.next').addClass('active');
	} 
    else {
        //$('div.socialFeedContainer div.next').removeClass('active');
	}
	updateChatter();
}

function bindChatterPagination() {
    $('div.socialFeedContainer div.prev').click(function () {
        //if ($(this).hasClass('active')) {
        currentChatterPage--;
        if (currentChatterPage < 0) {
            currentChatterPage = chatterPages - 1;
        }
        chatterIndex = currentChatterPage * chatterItemsPerPage;
        updateChatterPagination();
        //}
    });
    $('div.socialFeedContainer div.next').click(function () {
        //if ($(this).hasClass('active')) {
        currentChatterPage++;
        if (currentChatterPage > chatterPages - 1) {
            currentChatterPage = 0;
        }
        chatterIndex = currentChatterPage * chatterItemsPerPage;
        updateChatterPagination();
        //}
    });
}
// need a special parse date function for IE
function parseDate(str) {
    var v=str.split(' ');
    return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
} 

function createChatterObjects(data, socialType) {
	if (socialType == 'twitter') {
		$.each(
			$(data),
			function(tIndex, tItem) {
				var t = {
					"socialType": socialType,
					"created": parseDate(tItem.created_at),
					"description": ify.clean(tItem.text).replace(/<a href/gi, '<a target="_blank" href'),
					//"relativeTime": relative_time(tItem.created_at),
					"relativeTime": new Date(tItem.created_at).toRelativeTime(),
					"postId": tItem.id,
					"tweet": tItem.text,
			        "id_str": tItem.id_str,
                    "userName": tItem.user.name
				};
				chatterArray.push(t);
			}
		);
	}
	else {
		// facebook has potentially a lot more data points
		$.each(
			$(data.data),
			function(fIndex, fItem) {
				var newCreated = new Date(formatFBTime(fItem.created_time));
				var f = {
					"socialType": socialType,
					"created": newCreated,
					"message": ify.clean(fItem.message).replace(/<a href/gi, '<a target="_blank" href'),
					//"message": fItem.message,
					//"relativeTime": relative_time(dateFormat(newCreated, 'ddd mmm dd HH:MM:ss +0000 yyyy', false)),
					"relativeTime": newCreated.toRelativeTime(),
					"picture": fItem.picture,
					"link": fItem.link,
					"name": fItem.name,
					"source": fItem.source,
					"type": fItem.type,
					"likes": fItem.likes,
					"caption": ify.clean(fItem.caption).replace(/<a href/gi, '<a target="_blank" href'),
					"description": fItem.description,
					"postId": fItem.id.split("_")[1], // the id value contains the ID of the user/page + the id of the post, e.g. 30213905597_103716613032151
					"objectId": fItem.object_id
				};

				if (fItem.type == 'video' && fItem.properties != undefined && fItem.properties.text != undefined) {
					f.length = fItem.properties.text;
				}
				chatterArray.push(f);
			}
		);
	}
	
	// finally, if we're done, build the content on the screen
	if (feedsRetrieved == feedsToGet) {
	    buildChatter();
	}
}
function cleanFbLinks(t) {
	return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
		return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
	});
}
function buildChatter() {
	// sort
	chatterArray.sort(function(a, b) {
		var dateA = new Date(a.created);
		var dateB = new Date(b.created);
		if (dateA.valueOf() > dateB.valueOf()) return -1;
		if (dateA.valueOf() < dateB.valueOf()) return 1;
		return 0;
    });
        // trim the array if necessary
    chatterArray = chatterArray.slice(0, parseInt(maxItems));
	chatterCount = chatterArray.length;
	chatterPages = Math.ceil(chatterCount / chatterItemsPerPage);
	$('div.socialFeedContainer span.promoCount').html(chatterPages);
	bindChatterPagination();
	updateChatterPagination();
}

function updateChatter() {

    clearInterval(heightContainerInterval);
    heightContainerIntervalCount = 0;
    imgCount = 0;
	var subChatter = chatterArray.slice(chatterIndex, chatterIndex + chatterItemsPerPage);
	var twTemplate = $('div.socialTemplateContainer div.twPostContainer.template');
	var fbTemplate = $('div.socialTemplateContainer div.fbPostContainer.template');
	var subContainer = $('<div></div>');
	$(subContainer).addClass('subContainer');
	$(subContainer).hide();

	// remove old ones
	$('div.socialFeedContainer div.outerContainer div.subContainer').fadeOut('fast', function () {
	    $.each(
			$(subChatter),
			function (index, item) {
			    var description = item.description;
			    var pubDate = item.created;

			    if (item.socialType == 'twitter') {

			        var newTwitter = $(twTemplate).clone();
			        $(newTwitter).removeClass('template');
			        if (index < (chatterItemsPerPage - 1)) {
			            $(newTwitter).addClass('marginBottom');
			        }
			        $(newTwitter).find('span.tweet').html(description);
			        $(newTwitter).find('a.relativeTime').text(item.relativeTime);

			        $(newTwitter).find('a.relativeTime').attr('href', 'http://twitter.com/#!/' + twitterName + '/status/' + item.id_str);
			        $(newTwitter).find('a.twReply').attr('href', 'http://twitter.com/?status=@' + twitterName + '%20&in_reply_to_status_id=' + item.id_str + '&in_reply_to=' + twitterName);
			        $(newTwitter).find('a.twRetweet').attr('href', 'http://twitter.com/?status=RT%20@' + twitterName + '%20' + escape(item.tweet));
			        //$(newTwitter).find('div.twAccountName a').attr('href', 'http://twitter.com/#!/' + twitterName);
			        //$(newTwitter).find('div.twAccountName a').text("@" + twitterName);
			        //$(newTwitter).find('div.twAccountFullName').text(item.userName);

			        $(newTwitter).find('div.fbDateMonth').text(dateFormat(pubDate, 'mmm'));
			        $(newTwitter).find('div.fbDateDay').text(dateFormat(pubDate, 'd'));
			        $(newTwitter).show();
			        $(subContainer).append($(newTwitter));
			    }
			    else {
			        // this is facebook, capable of several different types of content
			        var newFacebook = $(fbTemplate).clone();
			        if (index < (chatterItemsPerPage - 1)) {
			            $(newFacebook).addClass('marginBottom');
			        }
			        $(newFacebook).find('div.relativeTime a').attr('href', 'http://www.facebook.com/' + facebookName + '/posts/' + item.postId);
			        $(newFacebook).find('div.relativeTime a').text(item.relativeTime);

			        //$(newFacebook).find('.message').html(item.message);
			        if (item.picture != null && item.picture != '') {
			            $(newFacebook).find('img.fbImage').load(function () {
			                imgsLoaded++;
			                setTimeout(function () {
			                    setChatterHeight($(subContainer));
			                }, 500);
			            });
			            $(newFacebook).find('img.fbImage').attr('src', item.picture);
			            imgCount++;
			        }
			        else {
			            $(newFacebook).find('div.fbImageContainer').remove();
			            $(newFacebook).find('div.fbCopyContainer').addClass('fullWidth');
			        }
			        switch (item.type) {
			            case "link":
			                $(newFacebook).find('div.fbMessage').html(item.message);
			                $(newFacebook).find('a.fbHyperlink').attr('href', item.link);
			                $(newFacebook).find('a.fbImageLink').attr('href', item.link);
			                $(newFacebook).find('a.fbHyperlink').text(item.name);
			                $(newFacebook).find('div.fbCaption').html(item.caption);
			                $(newFacebook).find('div.fbDescription').html(item.description);
			                break;
			            case "photo":
			                $(newFacebook).find('div.fbMessage').html(item.message);
			                if (item.picture != null && item.picture != '') {
			                    $(newFacebook).find('a.fbImageLink').attr('href', item.link);
			                }
			                $(newFacebook).find('a.fbHyperlink').attr('href', item.link);
			                $(newFacebook).find('a.fbHyperlink').text(item.name);
			                break;
			            case "video":
			                $(newFacebook).find('div.fbMessage').html(item.message);
			                var vidLink = $(newFacebook).find('.fbImageLink');
			                if (item.source.indexOf('vimeo') > -1 || item.source.indexOf('youtube') > -1) {
			                    $(vidLink).attr('href', item.source);
			                }
			                else {
			                    $(vidLink).attr('href', 'http://www.facebook.com/v/' + item.objectId);
			                }
			                $(vidLink).fancybox({
			                    'titleShow': false,
			                    'transitionIn': 'elastic',
			                    'transitionOut': 'elastic',
			                    'href': this.href,
			                    'type': 'swf',
			                    'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
			                });
			                $(newFacebook).find('div.fbVideoOverlay').show();
			                // that isn't working in chrome?
			                $(newFacebook).find('div.fbVideoOverlay').css('display', 'block');
			                $(newFacebook).find('a.fbHyperlink').attr('href', item.link);
			                $(newFacebook).find('a.fbHyperlink').text(item.name);
			                $(newFacebook).find('div.fbCaption').html(item.caption);
			                $(newFacebook).find('div.fbDescription').html(item.description);
			                $(newFacebook).find('div.fbVideoOverlay').click(function () {
			                    $(this).parent().find('a.fbImageLink').trigger('click');
			                });
			                break;
			            case "status":
			                $(newFacebook).find('div.fbMessage').html(item.message);
			                $(newFacebook).find('div.fbCopy').remove();
			                break;
			        }

			        $(newFacebook).find('div.month').text(dateFormat(pubDate, 'mmm'));
			        $(newFacebook).find('div.day').text(dateFormat(pubDate, 'd'));
			        $(newFacebook).show();
			        $(subContainer).append($(newFacebook));
			    }

			}
		);
	    $(this).remove();
	    $('div.outerContainer').append($(subContainer));
	    //setChatterHeight($(subContainer));
	    if ($('div.socialLoading').is(':visible')) {
	        $('div.socialLoading').fadeOut(200, function () {
	            $('div.outerContainer').fadeIn('fast');
	            $('div.socialNavigationContainer').fadeIn('fast');
	            if (imgCount == 0) {
	                setChatterHeight($(subContainer));
	            }
	        });
	    }
	    else if (imgCount == 0) {
	        setChatterHeight($(subContainer));
	    }
	    // in case the images haven't finished loading, set an interval to ensure we end up with the correct height eventually
	    /*
	    heightContainerInterval = setInterval(function () {
	    setChatterHeight($(subContainer));
	    }, 1000);
	    */
	});
}
function setChatterHeight(container) {
    var newHeight = $(container).actual('height');
    var outerContainer = $('div.socialFeedContainer div.outerContainer');

    if ($(outerContainer).css('height') != newHeight && !$(container).is(':visible')) {
        $(outerContainer).animate({
            height: newHeight
        }, 'fast', function () {
            $(container).fadeIn('fast');
        });
    }

    /*
    // check to see if all images have been loaded
    var imgs = $(container).find('img');
    var imgCount = imgs.length;
    var imgsLoaded = 0;

    for (i = 0; i < imgCount; i++) {
        var thisImg = $(imgs)[i];
        if (thisImg.complete || thisImg.readyState === 4) {
            imgsLoaded++;
        }
    }

    if (imgsLoaded == imgCount) {
        clearInterval(heightContainerInterval);
    }

    heightContainerIntervalCount++;

    if (heightContainerIntervalCount > 50) {
        clearInterval(heightContainerInterval);
    }
    */
}

window.ify = function() {
	var entities = {
		'"': '&quot;',
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;'
	};

	return {
		"link": function(t) {
			return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
				return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
			});
		},
		"at": function(t) {
			return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function(m, m1, m2) {
				return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
			});
		},
		"hash": function(t) {
			return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
				return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
			});
		},
		"clean": function(tweet) {
			if (tweet != undefined && tweet != '') {
				return this.hash(this.at(this.link(tweet))).replace('\n', '<br />');
			}
			else {
				return "";
			}
		}
	};
} ();
function relative_time(time_value) {
	// Tue Feb 01 12:44:15 +0000 2011
	var values = time_value.split(" ");
    var parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]);
	var date = new Date(parsed_date);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	var r = '';
	
	function formatTime(date) {
		var hour = date.getHours(),
                min = date.getMinutes() + "",
                ampm = 'AM';

		if (hour == 0) {
			hour = 12;
		} else if (hour == 12) {
			ampm = 'PM';
		} else if (hour > 12) {
			hour -= 12;
			ampm = 'PM';
		}

		if (min.length == 1) {
			min = '0' + min;
		}

		return hour + ':' + min + ' ' + ampm;
	}

	function formatDate(date) {
		var ds = date.toDateString().split(/ /),
                mon = months[date.getMonth()],
                day = date.getDate() + '',
                dayi = parseInt(day),
                year = date.getFullYear(),
                thisyear = (new Date()).getFullYear(),
                th = 'th';

		// anti-'th' - but don't do the 11th, 12th or 13th
		if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
			th = 'st';
		} else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
			th = 'nd';
		} else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
			th = 'rd';
		}

		if (day.substr(0, 1) == '0') {
			day = day.substr(1);
		}

		return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
	}

	delta = delta + (relative_to.getTimezoneOffset() * 60);
	//alert(date + " ::: " + relative_to + " ::: delta:" + delta);

	if (delta < 5) {
		r = 'less than 5 seconds ago';
	} else if (delta < 30) {
		r = 'half a minute ago';
	} else if (delta < 60) {
		r = 'less than a minute ago';
	} else if (delta < 120) {
		r = '1 minute ago';
	} else if (delta < (45 * 60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (2 * 90 * 60)) { // 2* because sometimes read 1 hours ago
		r = 'about 1 hour ago';
	} else if (delta < (24 * 60 * 60)) {
		r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else {
		if (delta < (48 * 60 * 60)) {
			r = formatTime(date) + ' yesterday';
		} else {
			r = formatTime(date) + ' ' + formatDate(date);
			// r = (parseInt(delta / 86400)).toString() + ' days ago';
		}
	}

	return r;
}
function formatFBTime(fbDate) {
	//2010-11-29T17:23:24+0000
	var arrDateTime = fbDate.split("T");
	var strTimeCode = arrDateTime[1].substring(0, arrDateTime[1].indexOf("+"));

	var arrDateParts = arrDateTime[0].split("-");
	var year = arrDateParts[0];
	var month = parseInt(arrDateParts[1] - 1);
	var day = arrDateParts[2];
	
	//var valid_date = new Date(arrDateTime[0]);
	//var valid_date = new Date(year, month, day);
	
	
	var valid_date = new Date();
	valid_date.setUTCFullYear(year);
	valid_date.setUTCMonth(month);
	valid_date.setUTCDate(day);
	
	var arrTimeCode = strTimeCode.split(":");
	valid_date.setUTCHours(arrTimeCode[0]);
	valid_date.setUTCMinutes(arrTimeCode[1]);
	valid_date.setUTCSeconds(arrTimeCode[2]);
	
	/*
	var valid_date = new Date();
	valid_date.setFullYear(year);
	valid_date.setMonth(month);
	valid_date.setDate(day);
	
	var arrTimeCode = strTimeCode.split(":");
	valid_date.setHours(arrTimeCode[0]);
	valid_date.setMinutes(arrTimeCode[1]);
	valid_date.setSeconds(arrTimeCode[2]);
	*/
	return valid_date;
}
Date.prototype.toRelativeTime = function(now_threshold) {
  var delta = new Date() - this;

  now_threshold = parseInt(now_threshold, 10);

  if (isNaN(now_threshold)) {
    now_threshold = 0;
  }

  if (delta <= now_threshold) {
    return 'Just now';
  }

  var units = null;
  var conversions = {
    millisecond: 1, // ms    -> ms
    second: 1000,   // ms    -> sec
    minute: 60,     // sec   -> min
    hour:   60,     // min   -> hour
    day:    24,     // hour  -> day
    month:  30,     // day   -> month (roughly)
    year:   12      // month -> year
  };
  var conversions = { millisecond:1 }
/*
  for (var key in conversions) {
    if (delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }
  */
  delta = delta / 1000;
  var r = "";
  
  if (delta < 5) {
		r = 'less than 5 seconds ago';
	} else if (delta < 30) {
		r = 'half a minute ago';
	} else if (delta < 60) {
		r = 'less than a minute ago';
	} else if (delta < 120) {
		r = '1 minute ago';
	} else if (delta < (45 * 60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (2 * 90 * 60)) { // 2* because sometimes read 1 hours ago
		r = 'about 1 hour ago';
	} else if (delta < (24 * 60 * 60)) {
		r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else {
		if (delta < (48 * 60 * 60)) {
			//r = formatTime(date) + ' yesterday';
			r = dateFormat(this, "h:MM TT") + ' yesterday';
		} else {
			//r = formatTime(date) + ' ' + formatDate(date);
			r = dateFormat(this, "h:MM TT") + ' ' + dateFormat(this, "mmm d");
			// r = (parseInt(delta / 86400)).toString() + ' days ago';
		}
	}

	return r;
  // pluralize a unit when the difference is greater than 1.
  /* 
  delta = Math.floor(delta);
  if (delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
  */
};

/*
 * Wraps up a common pattern used with this plugin whereby you take a String
 * representation of a Date, and want back a date object.
 */
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};

