var embedContent = {};
var inputs = [];

var errorDialog;
var deleteActivityDialog;
var deleteCommentDialog;
var deletePhotoDialog;
var addBuddyDialog;
var statusForm;
var retweetActivityDialog;
var retweetConfirmationDialog;
var signInDialog;
var signUpDialog;
var deleteNotificationDialog;

if(typeof console === "undefined") {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group",
                 "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
    }
}

function refreshMyIcons() {
	$('div.nasl-info img.user-icon, div#badge a.user img').each( function() {
		var el = $(this);
		var ts = (new Date()).getTime();
		var src = el.attr('origSrc');
		if ( ! src ) {
			src = el.attr('src');
		}
		if ( src.indexOf('?') != -1 ) {
			src += '&_=' + ts;
		} else {
			src += '?_=' + ts;
		}

		el.error( function() { imageError(this); } )
		  .attr('src',src);
	})
}

function renderTimestamp(time) {
	  var now, nowDate, shortMonths, days, shortDays, longAgo, timeDate, ampm, minutes, rounded, hour;
	  nowDate = new Date();
	  now = nowDate.getTime() / 1000;
	  
	  shortMonths = ["Jan", "Feb", "Mar",
	                "Apr", "May", "June",
	                "July", "Aug", "Sep",
	                "Oct", "Nov", "Dec"];
	  days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	  shortDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	  longAgo = now - time;
	  timeDate = new Date(time*1000);
	  ampm = (timeDate.getHours() >= 12 ? "PM" : "AM");
	  minutes = timeDate.getMinutes() < 10 ? "0" + timeDate.getMinutes() : timeDate.getMinutes();
	  longAgo = Math.floor(longAgo);
	  hour = (timeDate.getHours() > 12) ? timeDate.getHours() % 12 : timeDate.getHours();
	  hour = (hour === 0 ) ? 12: hour;
	  if (longAgo < 10) {
	    return 'less than 10 seconds ago';
	  } else if (longAgo < 60) {
	    return longAgo + ' seconds ago';
	  } else if (longAgo < (60 * 60)) {
	    rounded = Math.floor(longAgo / 60);
	    return (rounded === 1 ? '1 min ago' : rounded + ' mins ago');
	  } else if (longAgo < (24 * 60 * 60)) {
	    rounded = Math.floor(longAgo / (60 * 60));
	    return (rounded === 1 ? '1 hr ago' : rounded + ' hrs ago');
	  /*
	  } else if (longAgo < (2 * 24 * 60 * 60) && (timeDate.getDate() === (nowDate.getDate() - 1))) {
	    return ("Yesterday at " + hour + ":" + minutes + ampm);
	  } else if (longAgo < (7 * 24 * 60 * 60)) {
	    return (days[timeDate.getDay()] + " at " + hour + ":" + minutes + ampm);
	  */
	  } else {
	    return (shortMonths[timeDate.getMonth()] + " " +
	            timeDate.getDate() + " at " + hour + ":" + minutes + ampm);
	  }
}

function updateTimestamps(container) {
	var stamps = container.find('.timestamp')
	//var now = new Date().getTime() / 1000
	stamps.each(function(i) {
		var self = $(this)
		var timei = parseInt(self.find('.timei').text())
		self.find('.timeis').text(renderTimestamp(timei))
	})
}

function aimStringFormat(string, loggedInUser) {
	if (!loggedInUser) loggedInUser = "ti"
	var d = new Date()
	return string.replace("%n", loggedInUser).replace("%t", d.toLocaleTimeString()).replace("%d", d.toLocaleDateString());
}

var uploadDoneCB;
function uploadDone(ids) {
	if(!ids || ids.length == 0) {
		errorDialog.showErrors({
			title: "Status error",
			message: "Your status has not been posted.\nWe were unable to upload your photo at this time.\nPlease try again.",
			target: $('#statusInput')
		});
		enablePostButton();
		resetUploader();
		return;
	}

	uploadDoneCB (ids);
}

function resetUploader() {
	var uploader = document.getElementById('lifestreamStatusUploader');
	if(uploader != null) {
		uploader.reset();
	}
}

var statusCounter = {
	// add in reverse alpha order
	limits:  {
		'twitter': {max: 140, name:"Twitter",enabled:false},
		'myspace': {max: 140, name:"MySpace",enabled:false},
		'foursquare': {max: 140, name:"foursquare",enabled:false}
	},

	max: 251,
	workingMax: 251,

	hasPhotos: false,
	// change workingMax based on if uploading photos and cross-posting status
	setHasPhotos: function(hasPhotos) {
		if(!statusCounter.hasPhotos && hasPhotos && statusCounter.workingMax != statusCounter.max) {
			statusCounter.workingMax = statusCounter.workingMax - 25;
			statusCounter.hasPhotos = true;
			statusCounter.checkLength();
		} else if(statusCounter.hasPhotos && !hasPhotos && statusCounter.workingMax != statusCounter.max) {
			statusCounter.workingMax = statusCounter.workingMax + 25;
			statusCounter.hasPhotos = false;
			statusCounter.checkLength();
		}
	},

        serviceTipLabel: '<a href="javascript:void(0);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="has-graphic">?</span></a>',
        serviceTipText: "You are {0} character{1} over the {2} limit",
        photosTipText: "{0} characters + Photo link.  ",
        maxTipText: "Oops! You've reached the Lifestream Limit. Please shorten your thought a wee bit.",
        disabledTip: "{0} Please shorten your message.",

	init: function() {
		for(var l in statusCounter.limits) {
			statusCounter.limits[l].enabled = false;
		}
		statusCounter.workingMax = statusCounter.max;
		$("#currentCrossPost").find("input:checked").each(function(index){
			if(statusCounter.limits[$(this).val()]) {
				statusCounter.limits[$(this).val()].enabled = true;
				if(statusCounter.limits[$(this).val()].max < statusCounter.workingMax) {
						statusCounter.workingMax = statusCounter.limits[$(this).val()].max;
				}
			}
		});

		enablePostButton();

		if($('#statusInput.empty').size() > 0 || statusCounter.workingMax == statusCounter.max) {
			statusCounter.hide();
		} else {
			statusCounter.checkLength();
		}

	},

	checkLength: function() {
		var statusInput = $("#statusInput");
		if(statusInput.is('.empty')) {
			return;
		}

		var msgLen = statusInput.val().length;
			
		var serviceCount = 0;
			if(statusCounter.workingMax < statusCounter.max) {
			var remaining  = statusCounter.workingMax - msgLen;
			$("#statusCounter").html(remaining);
			$("#statusForm").addClass('counter');

			$("#statusNoticeText").html('');
			$("#statusNoticeHelp").html('');

			var sNames = '';
			var sTip = '';

			for(var s in statusCounter.limits) {
				var service = statusCounter.limits[s];
				var m = statusCounter.hasPhotos ? service.max - 25 : service.max;
				if(service.enabled && msgLen > m) {
					switch(++serviceCount) {
						case 1: sNames = service.name; break;
						case 2: sNames = service.name + ' and ' + sNames; break;
						default: sNames = service.name + ', ' + sNames; break;
					}
					var absRemain = Math.abs(remaining);
					var plural = absRemain == 1 ? '' : 's';
					var photosTip = statusCounter.hasPhotos ? statusCounter.photosTipText.replace("{0}", msgLen) : "";
					sTip = photosTip + statusCounter.serviceTipText.replace("{0}", absRemain).replace("{1}", plural).replace("{2}", sNames);
					$("#statusNoticeHelp").attr('title', sTip)
					                      .html(statusCounter.serviceTipLabel);
				}
			}
			if(remaining < 0) {
				disablePostButton(statusCounter.disabledTip.replace('{0}', sTip));
				$("#statusCounter").addClass('warn');
			} else {
				enablePostButton();
				$("#statusCounter").removeClass('warn');
			}

		} else {
			var byteLen = unescape(encodeURIComponent(statusInput.val())).length;
			if(byteLen >= statusCounter.max || statusCounter.justCropped) {
				if(byteLen > statusCounter.max) {
					statusInput.val(statusInput.val().substr(0,msgLen-1))
					                 .attr('scrollTop', statusInput.attr('scrollHeight'));
					statusCounter.justCropped = true;
				} else {
					statusCounter.justCropped = false;
				}
				$("#statusForm").addClass('counter');
				$("#statusNoticeHelp").attr('title', statusCounter.maxTipText)
				                      .html(statusCounter.serviceTipLabel);
			} else {
				statusCounter.hide();
			}
		}
	},

	hide: function() {
		$("#statusCounter").html('');
		$("#statusNoticeText").html('');
		$("#statusForm").removeClass('counter');
	}
};

function enablePostButton() {
	$('button.set-status').attr({'disabled':'', 'title':'Click to set your status'})
	                      .removeClass('disabled');
}

function disablePostButton(msg) {
	msg = msg || '';
	$('button.set-status').attr({'disabled':'disabled', 'title':msg})
	                      .addClass('disabled');
}

function Status(id) {
	this.id = id;
	this.element = $("#" + id);

	this.statusChanger = new Input("statusInput");

	this.statusChanger.doOnPrompt.push(statusCounter.hide);
	this.statusChanger.doOnClear.push(statusCounter.checkLength);
	
	this.statusHandler = function() {
		
		if (this.statusChanger.isEmpty()) {
			errorDialog.showMessage({
				title: "Status",
				message: "Please enter some text for your status.",
				target: this.element,
				duration: 3
			});
			
			return false;
		}
		
		var statusMsg = $("#statusInput").val();

      uploadDoneCB = this.postStatus;
	disablePostButton('uploading status');
      try {
         var uploader = document.getElementById('lifestreamStatusUploader');
         if (uploader != null)
         {
            var didPost = uploader.postImage(statusMsg);
            if (didPost) {
               return false;
            }
         }
      } catch (err) {
      }

      this.postStatus (null);
	enablePostButton();
      return false;
      
   }.bind(this);

   this.postStatus = function(ids) {
	statusCounter.hide();
	disablePostButton('uploading status');
      var statusMsg = $("#statusInput").val();
      
	   statusMsg = statusMsg.replace(/<\/(?:.|\s)*?>/g, "");
	   statusMsg = statusMsg.substr(0,statusCounter.max);
		taskPointer();
		this.statusChanger.showTask();
		
		if (typeof WIM === "undefined") {
         var idsStr = "";
         if (ids != null) {
            idsStr = ids.join(",");
         }
			$.post("/stream/set_status", {_a: window.authenticityToken, status: statusMsg, mediaIds: idsStr}, function(response) {
			    var object = JSON.parse(response);
			    if (object.status) {
			    	statArr = object.status.split("\n");
					$.each(statArr ,function(key, value){
						statArr[key] = $('<div/>').text(statArr[key]).html();
					});
					object.status = statArr.join("<br/>");
			    	$("#status").html(object.status);
			    	$("#status").append("<a id='clearStatus' href='javascript:;' onclick='clearStatusHandler()'>Clear</a>");
			        $("#statusCrossPostServices").html(object.statusCrossPostServices);
			        
			        $("#statusTimestamp").html(object.statusTimestamp);
			    	$("div#statusWrap").removeClass("emptyStatus");
					$("div#statusSrc").removeClass("emptyStatus");
					
					$("#statusCrossPostServices").html("");
					$("#statusCrossPostServices").append("<li class='aim'><img src='../img/favicons/aim.png' title='AOL Lifestream'/></li>");
					$("#statusCrossPostServices").append($("#currentCrossPost").html());
			    }
			    if (object.error) {
			    	errorDialog.showErrors({
						title: "Status error",
						message: "We were unable to update your status.\nPlease try again later.",
						errors: object.errors,
						target: this.element
					});
			    }
			    
			    defaultPointer();
				this.statusChanger.hideTask();
				enablePostButton();
			}.bind(this));
		} else {
         if (ids == null) {
           ids = new Array ();
         }

			WIM.call("/presence/setStatus", {statusMsg: statusMsg, mediaId: ids}, function(data, statusCode, statusText) {
				if (statusCode == 200) {
					statArr = statusMsg.split("\n");
					$.each(statArr ,function(key, value){
						statArr[key] = $('<div/>').text(statArr[key]).html();
					});
					statusMsg = statArr.join("<br/>");
					
					$("#status").html(aimStringFormat(statusMsg, WIM.aimId));
					$("#status").append("<a id='clearStatus' href='javascript:;' onclick='clearStatusHandler()'>Clear</a>");
					$("#statusTimestamp").text("now");
					$("#statusWrap").removeClass("emptyStatus");
					$("#statusSrc").removeClass("emptyStatus");
					$("#statusCrossPostServices").html("");
					$("#statusCrossPostServices").append("<li class='aim'><img src='../img/favicons/aim.png' title='AOL Lifestream'/></li>");
					$("#statusCrossPostServices").append($("#currentCrossPost").html());
					
				} else {
					errorDialog.showErrors({
						title: "Status error",
						message: "We were unable to update your status.\nPlease try again later.",
						errors: [statusText],
						target: this.element
					});
				}

				defaultPointer();
				this.statusChanger.hideTask();
				enablePostButton();
			}.bind(this));
		}

      try {
         resetUploader();
      } catch (err) {
      }
		return false;

	}.bind(this);

	this.element.submit(this.statusHandler);
	this.element.keydown(this.keydownHandler);
	this.element.keyup(statusCounter.checkLength);
	this.element.bind('paste', function(){setTimeout(statusCounter.checkLength, 250)});
	this.element.change(this.changeHandler);

	statusCounter.init();

}

function escapeHtml(text) {
   if (! text ) { return ''; }
   return text.replace(/&/g,'&amp;').
                replace(/>/g,'&gt;').
                replace(/</g,'&lt;').
                replace(/"/g,'&quot;');
}

function imageError(image) {
	$(image).attr('origSrc',$(image).attr('src'))
			.attr("onerror","")
			.attr('src','http://api.oscar.aol.com/expressions/getAsset?id=00052b000020d3&f=native&type=buddyIcon');
	return true;
}

function initializeControls(scope) {
	if (scope == null) {
		scope = $(document.body);
	}

	scope.find("a.user, div.searchable a, div.media a, .timestamp a, div.commentHtml a").not("a.aim-service").not("a.timeis").not("a.nlocal").attr("target", "_blank");
	scope.find("a.help").attr("target", "help");
	scope.find("a.user img, li.user img, img.user").error(function(event) {
		imageError(event.target);
	});
	scope.find(".input-task").removeClass("input-task");
	
	var textFields = scope.find("textarea.comment");
	textFields.each(function() {
		var id = $(this).attr("id");
		if (!inputs[id]) {
			inputs[id] = new Input(id);
		}
	});
}

function addLikeHandler(event) {
	var anchor = $(this);
	var href = anchor.attr("href");
	var splits = parameters(fragment(href));
	var activityKey = splits[1];

	taskPointer();
	
	var action = "/stream/add_like";
	
	$.post(action, {
		"_a": window.authenticityToken,
		activityKey : activityKey
	}, function(response) {
		var object = JSON.parse(response);
		var ul = $(escapeId("ul#feedback:" + activityKey));
		ul.closest('div.comments').removeClass('empty');
		if (object.rendered) {
			ul.find("li.likes").remove();
			ul.prepend(object.rendered);

			anchor.html('Unlike');
			anchor.attr('title', 'unlike activity');
			anchor.removeClass('like').addClass('delete-like');

			reportStats('LSTW:AddLike');
		}

		if (object.error) {
			errorDialog.showErrors({
				title: "Like error",
				message: "We were unable to mark this activity as liked.\nThe activity may not be available.",
				errors: object.errors,
				target: ul
			});
		}

		defaultPointer();
	});

	event.preventDefault();
	event.stopPropagation();
}

function deleteLikeHandler(event) {
	var anchor = $(this);
	var href = anchor.attr("href");
	var splits = parameters(fragment(href));
	var activityKey = splits[1];

	taskPointer();
	
	var action = "/stream/delete_like";
	
	var data = {
		"_a": window.authenticityToken,
		activityKey : activityKey
	};

	var callback = function(response) {

		var object = JSON.parse(response);

		var li = $(escapeId("ul#feedback:" + activityKey) + " li.likes");
		
		if (object.rendered) {
			li.replaceWith(object.rendered);

			reportStats('LSTW:DeleteLike');
		} else {
			li.fadeOut("fast", function() {
				$(this).slideUp("fast", function() {
					var commentParent = $(this).closest('div.comments');
					$(this).remove();
					if(commentParent.find('li.comment[^id=comment], li.likes').size() == 0) {
						commentParent.addClass('empty');
					}
				});
			});
			reportStats('LSTW:DeleteLike');
		}

		if (object.error) {
			errorDialog.showErrors({
				title: "Like error",
				message: "We were unable to remove the like from this activity.\nThe like or activity may have been removed.",
				errors: object.errors,
				target: li
			});
		} else {
                        anchor.html('Like');
                        anchor.attr('title', 'like activity');
                        anchor.removeClass('delete-like').addClass('like');
		}

		defaultPointer();
	};

	$.post(action, data, callback);
	
	event.preventDefault();
	event.stopPropagation();
}

function moreCommentsHandler(event) {
	var href = $(this).attr("href");
	var splits = parameters(fragment(href));
	var activityKey = splits[1];

	var ul = $(escapeId("ul#feedback:" + activityKey));
	ul.find('p.control-more-comments').hide();
	ul.find('p.control-less-comments').show();
	if(ul.find('.fetched').size() > 0) {
		ul.find('li:not(.more-comments)').show();
	} else {
	var li = $(this).closest("li.comment");
	
	taskPointer();
	li.addClass("input-task");
	
	$.get("/stream/more_comments", {
		"activityKey": activityKey
	}, function(response) {
		var object = JSON.parse(response);
		var ul = li.closest("ul");
		if (object.rendered) {
			ul.find('li[id^=comment]').remove();
			ul.append(object.rendered);
			ul.find('a.view-all').html('View all <span class="comment-count">'+ul.find('li[id^=comment]').size()+'</span> comments');
			initializeControls();

			reportStats('LSTW:ExpandComments');
		}
		
		if (object.error) {
			errorDialog.showErrors({
				title: "Comments error",
				message: "We were unable to retrieve comments for this activity.\nPlease try again later.",
				errors: object.errors,
				target: ul
			});
			ul.find('p.control-more-comments').show();
			ul.find('p.control-less-comments').hide();
			li.removeClass("input-task");
		}
		
		defaultPointer();
		// indicate we've already fetched once
		li.addClass('fetched');
	});
}
	
	event.preventDefault();
}

function lessCommentsHandler(event) {
	var href = $(this).attr("href");
	var splits = parameters(fragment(href));
	var activityKey = splits[1];

	var ul = $(escapeId("ul#feedback:" + activityKey));
	ul.find('p.control-more-comments').show();
	ul.find('p.control-less-comments').hide();
	ul.find('li[id^=comment]').slice(0,-2).hide();
	
	event.preventDefault();
}


function addCommentHandler(event) {
	var form = $(event.target).closest("form");
	var activityKey = form.find("input:hidden[name=activityKey]").val();
	var input = inputs["input:" + activityKey];
	
	if (input.isEmpty()) {
		errorDialog.showMessage({
			title: "Comment",
			message: "Please enter some text for your comment.",
			target: event.target,
			duration: 3
		});
		
		return false;
	}
	
	var action = "/stream/add_comment";
	var comment = input.value();
	var twitterName= "";
	var activity = $(this).closest('li.activity');
	var link = activity.find('dl.service a.twitter-service');
	if(link.size() > 0) {
		twitterName = link.attr('href').replace('http://twitter.com/','');
	}	
	comment = comment.replace("@"+twitterName,"");
	taskPointer();
	input.showTask();

	$.post(action, {
		"_a": window.authenticityToken, 
		activityKey : activityKey,
		comment : comment
	}, function(response) {
		var object = JSON.parse(response);
		var div = $(escapeId("li#activity:" + activityKey));
		if (object.rendered) {
			input.clear();
			div.find('div.comments').removeClass('empty');
			var id = $(escapeId("ul#feedback:" + activityKey));
			id.append(object.rendered);
			var countElem = div.find('span.comment-count:first');
			if(countElem.size() > 0) {
				try {
					var count = parseInt(countElem.text());
					count++;
					countElem.html(count);
				} catch(x) {
				}
			}
			initializeControls(id);

			reportStats('LSTW:AddComment');
		}

		if (object.error) {
			errorDialog.showErrors({
				title: "Comment error",
				message: "We were unable to add this comment.\nThe activity may not be available.",
				errors: object.errors,
				target: div
			});
		} else if (object.thirdPartyOnly) {
			// optional behavior
		} else if (object.serviceFail) {
			errorDialog.showErrors({
				title: "Unable to post comment",
				message: "We were unable to post your comment to " + object.serviceFail + ".  The activity may not be available for commenting.",
				errors: null,
				target: div
			});
		}

		defaultPointer();
		input.hideTask();
	});

	event.preventDefault();
	event.stopPropagation();
}

function deleteCommentHandler(event) {
	var href = $("#deleteCommentDialog input.dialog-data").val();
	var splits = parameters(fragment(href));
	var activityKey = splits[1];
	var commentId = splits[2];
	
	var action = "/stream/delete_comment";
	taskPointer();
	$.post(action, {
		"_a": window.authenticityToken,
		activityKey : activityKey,
		commentId : commentId
	}, function(response) {
		var object = JSON.parse(response);
		var div = $(escapeId("li#comment:" + activityKey + ":" + commentId));
		if (object.deleted) {
			div.fadeOut("fast", function() {
				$(this).slideUp("fast", function() {
					var commentParent = $(this).closest('div.comments');
					$(this).remove();
					if(commentParent.find('li.comment[^id=comment], li.likes').size() == 0) {
						commentParent.addClass('empty');
					} else {
						var countElem = commentParent.find('span.comment-count:first');
						if(countElem.size() > 0) {
							try {
								var count = parseInt(countElem.text());
								count--;
								countElem.html(count);
								if(count < 3) {
									commentParent.find('.control-more-comments  a.view-all').click();
									setTimeout(function(){commentParent.find('.more-comments').hide();}, 750);
								}
							} catch(x) {
							}
						}
					}
				});
			});

			reportStats('LSTW:DeleteComment');
		}
		
		if (object.error) {
			errorDialog.showErrors({
				title: "Comment error",
				message: "We were unable to remove this comment.\nThe comment or activity may have been removed.",
				errors: object.errors,
				target: div
			});
		}
		
		defaultPointer();
	});

	event.preventDefault();
	event.stopPropagation();
}

function deletePhotoHandler(event) {
	var href = $("#deletePhotoDialog input.dialog-data").val();
	var splits = parameters(fragment(href));
	var photoId = splits[1];

	var action = "/photos/delete_photo";
	taskPointer();
	$.post(action, {
		"_a": window.authenticityToken,
		pid : photoId
	}, function(response) {
		var object = JSON.parse(response);
		if (object.deleted) {
			window.location.href = splits[2];
		}

		if (object.error) {
			errorDialog.showErrors({
				title: "Photo error",
				message: "We were unable to remove this photo.\nIt may have already been removed.",
				errors: object.errors
			});
		}
		
		defaultPointer();
	});

	event.preventDefault();
	event.stopPropagation();
}

function retweetActivityHandler(event) {
	var href = $("#retweetActivityDialog input.dialog-data").val();
	var splits = parameters(fragment(href));
	var activityKey = splits[1];

	$.post('/stream/retweet_activity', {
		activityId : activityKey
	}, function(response) {
		var respObj = JSON.parse(response);
		if(respObj.ok) {
			// don't have a good way to get the twitter name back, so we extract from the url
			var name, link = '';
			link = $(escapeId('li#activity:' + activityKey)).find('dl.service a.twitter-service');
			if(link.size() > 0) {
				name = link.attr('href').replace('http://twitter.com/','');
				if(name.endsWith('s')) {
					name = "@" + name + "'";
				} else {
					name = "@" + name + "'s";
				}
			}
			$('#retweetConfirmation').html(name + ' post has been Retweeted.');
			retweetConfirmationDialog.open();
			setTimeout(function(){retweetConfirmationDialog.close();}, 1500);
		} else {
			$('#retweetConfirmation').html('Unable to Retweet at this time.');
			retweetConfirmationDialog.open();
			setTimeout(function(){retweetConfirmationDialog.close();}, 3000);
		}
	});

	event.preventDefault();
	event.stopPropagation();
}
function deleteNotificationHandler(event) {
	var href = this.href;
	var splits = parameters(fragment(href));
	var activityKey = splits[1];
	var action = "/stream/delete_activity";
	
	taskPointer();
	$.post(action, {
		"_a": window.authenticityToken,
		activityKey : activityKey
	}, function(response) {
		var object = JSON.parse(response);
		var div = $(escapeId("li#activity:" + activityKey));
		if (object.deleted) {
			var isDM = $(div).hasClass("message");
			var msg = isDM ? "You have no new direct messages." : "You have no new notifications.";
			var parent = div[0].parentNode;
			div.fadeOut("fast", function() {
				$(this).slideUp("fast", function() {
					$(this).remove();
					if(parent.getElementsByTagName("li").length == 0) {
						parent.innerHTML = "<li class=\"notifications\"><p>" + msg + "</p></li>";
						isDM ? $("#dmExpander").remove() : $("#notificationsExpander").remove();
					}
				});
			});
			reportStats('LSTW:DeleteActivity');
		}

		if (object.error) {
			errorDialog.showErrors({
				title: "Activity error",
				message: "We were unable to remove this notification.\nIt may have already been removed.",
				errors: object.errors,
				target: div
			});
		}
		
		defaultPointer();
	});

	event.preventDefault();
	event.stopPropagation();
}
function deleteActivityHandler(event) {
	var href = $("#deleteActivityDialog input.dialog-data").val();
	var splits = parameters(fragment(href));
	var activityKey = splits[1];

	var action = "/stream/delete_activity";
	
	taskPointer();
	$.post(action, {
		"_a": window.authenticityToken,
		activityKey : activityKey
	}, function(response) {
		var object = JSON.parse(response);
		var div = $(escapeId("li#activity:" + activityKey));
		if (object.deleted) {
			div.fadeOut("fast", function() {
				$(this).slideUp("fast", function() {
					$(this).remove();
				});
			});

			reportStats('LSTW:DeleteActivity');
		}
      if (object.statusCleared) {
         $("p#status").html("");
		   $("div#statusWrap").addClass("emptyStatus");
		   $("div#statusSrc").addClass("emptyStatus");
      }

		if (object.error) {
			errorDialog.showErrors({
				title: "Activity error",
				message: "We were unable to remove this activity.\nIt may have already been removed.",
				errors: object.errors,
				target: div
			});
		}
		
		defaultPointer();
	});

	event.preventDefault();
	event.stopPropagation();
}

function addBuddyHandler(event) {
	var input = $("form#addBuddy input[type=submit]");
	var group = $("#addBuddy-group").val();
	var buddy = $("#addBuddy-buddy").val();

	taskPointer();
	
	WIM.call("/buddylist/addBuddy", {buddy: buddy, group: group}, function(data, statusCode, statusText) {
		if (statusCode == 200) {
			input.fadeOut();
		} else {
			errorDialog.showErrors({
				title: "Add Buddy error",
				message: "We were unable to add this person to your Buddy List.\nPlease try again later.",
				errors: [statusText],
				target: input
			});
		}
		
		defaultPointer();
	});

	event.preventDefault();
	event.stopPropagation();
}

function initializeListeners() {
	$("a.expand").live("click", function(event) {
		var href = $(this).attr("href");
		var splits = parameters(fragment(href));
		var activityKey = splits[1];
		var index = splits[2];
		var element = $(escapeId("div#media:" + activityKey + ":" + index ));

		if (element.hasClass("expand-down")) {
			element.removeClass("expand-down");
			element.addClass("collapse-up");
			$(this).attr("title", "collapse");
		} else {
			element.removeClass("collapse-up");
			element.addClass("expand-down");
			$(this).attr("title", "expand");
		}
		event.preventDefault();
	});

	$("a.load").live("click", function(event) {
		var href = $(this).attr("href");
		var splits = parameters(fragment(href));
		var activityKey = splits[1];
		var index = splits[2];
		var object = splits[3];
		
		$(escapeId("li#media:" + activityKey + ":" + index + ":" + object)).html(
				embedContent[activityKey + ":" + index + ":" + object]);
		$(escapeId("div#media:" + activityKey + ":" + index)).removeClass("expand-down");

		event.preventDefault();
		reportStats('LSTW:ViewVideo');
	});

	$("a.like").live("click", addLikeHandler);
	$("a.delete-like").live("click", deleteLikeHandler);

	$("a.comment").live("click", function(event) {
		var href = $(this).attr("href");
		var splits = parameters(fragment(href));
		var activityKey = splits[1];

		var element = $(escapeId("div#comment:" + activityKey));
		if (element.is(":hidden")) {
			elem = inputs["input:" + activityKey];
			
			var comment_link = $(this).closest('a.comment');		
			if(jQuery.trim(comment_link.html())=="@Reply"){
				var twitterName= "";
				var activity = $(this).closest('li.activity');
				var link = activity.find('dl.service a.twitter-service');
				if(link.size() > 0) {
					twitterName = link.attr('href').replace('http://twitter.com/','');
				}				
				
				elem.atTwitter=true;
				elem.atTwitterName=twitterName;
			}else{
				elem.atTwitter=false;
				elem.atTwitterName="";
			}
		}
		element.slideToggle(function() {
			var commentParent = $(this).closest('div.comments');
			if (element.is(":visible")) {
				inputs["input:" + activityKey].focus();
				commentParent.removeClass('empty');
			} else if(commentParent.find('li.comment[^id=comment], li.likes').size() == 0) {
				commentParent.addClass('empty');
			}
		});
		
		event.preventDefault();
	});
	
	$("p.control-more-comments a").live("click", moreCommentsHandler);
	$("p.control-less-comments a").live("click", lessCommentsHandler);

	$("div.add-comment button[type=submit]").live("click", addCommentHandler);
	
	$("a.delete-activity").live("click", function(evt) { var ret = deleteActivityDialog.open(evt); $('#deleteActivityDialog button.submit').focus(); return ret; });
	$("a.delete-notification").live("click", deleteNotificationHandler);
	$("a.delete-comment").live("click", function(evt) { var ret = deleteCommentDialog.open(evt); $('#deleteCommentDialog button.submit').focus(); return ret; });

	$("a.delete-photo").live("click", function(event) {
		deletePhotoDialog.open(event);
		$('#deletePhotoDialog button.submit').focus();
		deletePhotoDialog.move($(event.target).closest(".photobox").offset().top);
	});
	
	$("a.retweet-activity").live("click", function(event) {
		try{
		var activity = $(this).closest('li.activity');
		var link = activity.find('dl.service a.twitter-service');
		if(link.size() > 0) {
			$('#retweetUser').html(link.attr('href').replace('http://twitter.com/',''));
		}
        	$('#retweetMsg').html(activity.find('.titleHtml h4').html());
		retweetActivityDialog.open(event);
		} catch(x) {}
	});
	
	$("textarea.comment").live("keyup", function(event) {
		var value = $(event.target).val();
		if (value.length > 1024) {
			errorDialog.showMessage({
				title: "Comment",
				message: "Please limit your comment to 1024 characters.",
				target: event.target,
				duration: 3
			});
			
			$(this).val(value.substring(0, 1024));
			event.preventDefault();
			event.stopPropagation();
		}
	});
}


// those document ready things that apply to the stream, so we can reapply when refreshing the stream
function initStream() {
	// crop long names
	$('a.user-title').each( function() {$(this).html(crop($(this).text(),55));});

	// add stats collection
	$('.buddyIcon a.user, .titleHTML a.user').live('click', function(){reportStats('LSTW:ActivitySnClick')});
	$('.comments a.user').live('click', function(){reportStats('LSTW:CommentSnClick')});
	$('a.service-icon').live('click', function(){reportStats('LSTW:FavIconClick')});
	$('.linkUrl a').live('click', function(){reportStats('LSTW:FollowLink')});
	$('.media .photos a').live('click', function(){reportStats('LSTW:ViewPhoto')});
	$('a.retweet-activity').live('click', function(){reportStats('LSTW:RetweetNow')});
}
$(document).ready( function() {
	BrowserDetect.init();
	browserCheck();
	initStream();

	if(window.location.pathname == '/') { $('#refreshStream').show(); }

	$("ul.badge-navigation > li:first-child, ul.legal > li:first-child").css("border", "none");
	//$("input.search-button").attr("value", "");
	
	// Edit buddy icon for badge
	$('div#badge div.user-icon-wrapper')
	.mouseenter(
			function() {
				$(this).find('p.user-icon-edit').css('display','block');
			})
	.mouseleave(
			function() {
				$(this).find('p.user-icon-edit').css('display','none');
			});
	$('div#badge p.user-icon-edit a').click( function() {
		if(typeof(WIM)!="undefined") {
			var displayName = $('div#badge h2.user a').text();
			var win = window.open( "http://o.aolcdn.com/aim/gromit/iconuploader/current.en-us/Main.html?env=prod&lang=en-us&aimsid=" + WIM.aimsid + "&displayId=" + displayName,"editIcon","resizeable=yes,width=487,height=308,directories=no,titlebar=no,scrollbars=no,menubar=no,toolbar=no,location=no");
			var id = setInterval( function() {if ( win.closed ) {refreshMyIcons();clearInterval(id);}}, 50 );

			return false;
		}
	});
	$('button.button').mousedown(function(){
		$(this).addClass("lsgreenActive");
		//alert("mousedown");
	})
	
	$("#notificationsExpander a").prepend("&#x25BC; ");
	$("#notificationsExpander a, div.notifications h2 a").click(function(event) {
		var list = $(".notificationsWrapper ul.notifications li.notification-toggle");
		list.slideDown();
		$("#notificationsExpander").fadeOut("fast");
		$("#notificationsCollapser").fadeIn("fast");
		event.preventDefault();
		event.stopPropagation();
	});
	
	var collapser = $("#notificationsCollapser a");
	collapser.prepend("&#x25B2; ");
	collapser.click(function(event) {
		var list = $(".notificationsWrapper ul.notifications li.notification-toggle");
		list.slideUp();
		$("#notificationsCollapser").fadeOut("fast");
		$("#notificationsExpander").fadeIn("fast");
		event.preventDefault();
		event.stopPropagation();
	});
	
	$("#dmExpander a").prepend("&#x25BC; ");
	$("#dmExpander a").click(function(event) {
		var list = $(".dmWrapper ul.notifications li.notification-toggle");
		list.slideDown();
		$("#dmExpander").fadeOut("fast");
		$("#dmCollapser").fadeIn("fast");
		event.preventDefault();
		event.stopPropagation();
	});
	
	var dmcollapser = $("#dmCollapser a");
	dmcollapser.prepend("&#x25B2; ");
	dmcollapser.click(function(event) {
		var list = $(".dmWrapper ul.notifications li.notification-toggle");
		list.slideUp();
		$("#dmCollapser").fadeOut("fast");
		$("#dmExpander").fadeIn("fast");
		event.preventDefault();
		event.stopPropagation();
	});
	
	errorDialog = new Dialog("errorDialog");
	statusForm = new Status("statusForm");
	 
	deleteActivityDialog = new Dialog("deleteActivityDialog", deleteActivityHandler);
	//deleteNotificationDialog = new Dialog("deleteNotificationDialog", deleteNotificationHandler);
	deleteCommentDialog = new Dialog("deleteCommentDialog", deleteCommentHandler);
	deletePhotoDialog = new Dialog("deletePhotoDialog", deletePhotoHandler);
	addBuddyDialog = new Dialog("addBuddyDialog", addBuddyHandler);
	retweetActivityDialog = new Dialog("retweetActivityDialog", retweetActivityHandler);
	retweetConfirmationDialog = new Dialog("retweetConfirmationDialog");
	signInDialog = new Dialog("signInDialog");
	signUpDialog = new Dialog("signUpDialog");
	
	$("dd.profile-options input.sms-selector").click(function(event) {
		var input = $(this);
		var enabled = input.is(":checked");
		var action = "/settings/" + (enabled ? "enable" : "disable") + "_sms";
		
		taskPointer();
		$.post(action, {
			"_a": window.authenticityToken,
			"followingId": input.val()
		}, function(response) {
			var object = JSON.parse(response);
			if (object.success) {
				/* TODO: show success */
			}
			if (object.error) {
				errorDialog.showErrors({
					title: "Subscription error",
					message: "We were unable to change your SMS update subscription.\nPlease try again later.",
					errors: object.errors,
					target: input
				});
			}
			
			defaultPointer();
		});
	});
	
	$("form#addBuddy input[type=submit]").click(function(event) {
		var input = $(this);
		var buddy = $("#buddyId").val();
		
		taskPointer();
		$("#addBuddyDialog p").text("Add " + buddy + " to your AIM Buddy List");
		$("#addBuddy-buddy").attr("value", buddy);
		
		WIM.call("/buddylist/get", {}, function(data, statusCode, statusText) {
			if (statusCode == 200) {
				$("#addBuddy-group").empty();
				$.each(data.groups, function() {
					$("#addBuddy-group").append("<option value='"+this.name+"'>"+this.name+"</option>");
				});
				addBuddyDialog.open(event);
			} else {
				errorDialog.showErrors({
					title: "Add Buddy error",
					message: "We were unable to add this person to your Buddy List.\nPlease try again later.",
					errors: [statusText],
					target: input
				});
			}
			defaultPointer();
		});
		
		event.preventDefault();
		event.stopPropagation();
	});
	
	$("#signInLink, a.signin").click( function(event) {
		$("#signInDialog").show();
		$("#signUpDialog").hide();
		$('#landing #overlay').show();
		var p = $(".snsContainer")[0];
		AsnsSignIn(p, 0, 0 );
		return false;
	});
	
	$(".signup").click( function(event) {
		$("#signUpDialog").show();
		$("#signInDialog").hide();
		$('#landing #overlay').show();
	});
	
	$(".signInButton").click( function(event) {
		$('#signUpDialog').hide();
		if(this.className.indexOf("fb_button") > -1) {
			$('#landing #overlay').hide();
			launchFB();
		} else {
			$("#signInLink").trigger("click");
		}
	});
	
	$(".createAccount").click( function(event) {
		$('#signUpDialog').hide();
		$('#landing #overlay').hide();
		var x = (screen.width - 965)/2; var y = (screen.height - 785)/2;
    	var url = "https://new.aol.com/productsweb/?promocode=825967";
    	var oafbloginwin = window.open(url,'create_account','resizable=yes,width=965,height=785,directories=no,titlebar=no,status=no,menubar=no,toolbar=no,scrollbars=yes,location=no,left='+x+',top='+y);
    	if(oafbloginwin) oafbloginwin.focus()
	});
    
	$('#refreshStream').live('click', refreshStreamHandler);

	initializeControls();
	initializeListeners();
	if(isHighContrast()) {
		$('body').addClass('high-contrast');
		// show text for that is usually hidden for graphic
		$('.has-graphic').removeClass('has-graphic');

		// search, post focus
		$('a').live('focus',function(){$(this).css('border','1px dashed important!');});

		// use text in place of some buttons
		// search button in nav
		$('input.search-button').attr('value', 'Search');

		// 'remove' button on settings page
		$('#accountsList ul.controls a.remove').html('remove');

		// make service icons actual img elements
		$('#currentCrossPost label.service-icon').not('hc_updated').each( function() {
                        var icon = document.createElement('img');
			icon.src = computeServiceIconUrl($(this));
			icon.style.cursor = 'pointer';
			$(this).addClass('hc_updated');
                        $(this).children().replaceWith(icon);
                });
		$('#crossPostEdit .service-icon, li.activity .service-icon').each( function() {
                        var icon = document.createElement('img');
                        icon.src = computeServiceIconUrl($(this));
                        $(this).prepend(icon);
                });

	}
	
	if(location.search.indexOf("showsignin=1") > -1) {
		try {
			$("#signInLink").trigger("click");
		} catch(err) { };
	}
});


$(window).load(function() {
	$("a.user img").each(function() {
		if ((typeof this.naturalWidth != "undefined" && this.naturalWidth === 0) || this.readyState == "uninitialized") {
			imageError(this);
		}
	});
});

$(document).ready(function() {
	$("#stream, #results").each(function() {
		var elem = $(this);
		updateTimestamps(elem);
		window.setInterval(function() {updateTimestamps(elem)}, 60000);
	})
	// Maxlength for textarea
	$('textarea').each(function() {
		if(/^[0-9]+$/.test($(this).attr('maxlength'))) {
			$(this).keyup(function() {
				var max = parseInt($(this).attr('maxlength'));
				if($(this).val().length > max) {
					$(this).val($(this).val().substr(0, max));
					$(this).attr('scrollTop', $(this).attr('scrollHeight'));
					return false;
				}
			});
			$(this).blur(function() {
				var max = parseInt($(this).attr('maxlength'));
				if($(this).val().length > max) {
					$(this).val($(this).val().substr(0, max));
					$(this).attr('scrollTop', $(this).attr('scrollHeight'));
					return false;
				}
			});
		}
	});
});

function normalize_sn(sn) {
         if ( typeof(sn) === 'undefined') {
             return sn;
         }
         if ( sn.indexOf("@") !== -1 ) {

             return sn.toLowerCase();
         } else {
             var re = new RegExp("[^A-z0-9]","gi");
             return sn.replace(re,'').toLowerCase();
         }
      }
function compareNormalized_sn(sn1,sn2) {
          return (normalize_sn(sn1) === normalize_sn(sn2));  
      }

function lifestream_SNS_skin(){
	alert("within sns skin");
	var cssLink = document.createElement("link") 
    cssLink.href = "/css/lifestream_snslogin_skin.css"; 
    cssLink .rel = "stylesheet"; 
    cssLink .type = "text/css"; 

    var doc=document.getElementById("loginframe").contentWindow.document 
    alert(doc);	
    //doc.body.appendChild(cssLink);
	
}
function getURLAuth(){
	//return "&k=red-wim&s=lifestream66";
	if(typeof(WIM)=="undefined"){return null;}
	
	return "&aimsid="+ WIM.aimsid;
} 
function getURLBase(){
	//return "http://reddev-l23.tred.aol.com:8000";
	if(typeof(WIM)=="undefined"){
		return null;
	}
	return WIM.apiBaseURL;
}

function moreLikes(actId){

   var likeUsers = document.getElementById("likeUsers:"+actId);

   if(likeUsers.className=="likeUsers_show"){
      likeUsers.className="likeUsers_hide";
   }else if(likeUsers.className=="likeUsers_hide"){
      likeUsers.className="likeUsers_show";
   }else{

	  var params = { "activityKey": actId };
	  var tk = getParameter("tk");
	  if ( tk != undefined ) {
		  params["tk"] = tk;
	  }
      $.get("/stream/more_likes", params,
      function ( response ) {
         likeUsers.className="likeUsers_show";
         var object = JSON.parse(response);
         if (object.rendered) {
            likeUsers.innerHTML += object.rendered;
         }
      });
   }

	reportStats('LSTW:ExpandLikes');
}

function getActivity(actId){
	//this is here for testing...
	//if(typeof(WIM)=='undefined'){ var WIM = new Array; WIM.aimId = "linnydev00"; }
	
	var url = getURLBase()+"/lifestream/getActivity?f=json"+getURLAuth()+"&activityId="+actId+"&c=?";
	var likeUsers = document.getElementById("likeUsers:"+actId);
	//var likeUsers = $("#likeUsers:" + actId)[0];
	
	if(likeUsers.className=="likeUsers_show"){
		likeUsers.className="likeUsers_hide";
	}else if(likeUsers.className=="likeUsers_hide"){
		likeUsers.className="likeUsers_show";
	}else{
		
		$.getJSON(url,
				function ( result ) {
					var grp = result.response.data.activity.likeUsers;
					likeUsers.className="likeUsers_show";
					for ( var x in grp) {
						if(!compareNormalized_sn(WIM.aimId,grp[x].aimId)){
							likeUsers.innerHTML+="<li><a href='"+grp[x].profileUrl+"' >"+grp[x].displayName+"</a></li>";
						}
					}
		});
	}
}

function refreshStreamHandler(event) {
	$(this).addClass('working');
	taskPointer();

	$.post("/stream/refresh_stream", {filterType: $('#filterType').attr('filter')}, function(response) {
		var result = JSON.parse(response);
		if(result.html && result.html != '') {
			var stream = $('#stream');
			stream.hide();
			stream.html(result.html);
			stream.slideDown('slow');
			inputs = {};
			initializeControls(stream);
			initStream();
		}
		$('#refreshStream').removeClass('working');
		var maLink = $("a#moreActivities");
		if ( maLink.size() > 0 ) {
			maLink.removeClass('hide-view-more');
			if ( maLink.attr('origHref') ) {
				maLink.attr('href', maLink.attr('origHref') );
			}
		}
		defaultPointer();

		reportStats('LSTW:Refresh');
	});

	event.preventDefault();
}

function browserSupported(){
	var browserName=navigator.appName; 
	var browserVer=parseInt(navigator.appVersion); 
	
	//List unsupported browsers and version
	if( (browserName=="Microsoft Internet Explorer" && getIEVersion() < 7) ||
		(browserName=="Firefox" && browserVer < 3) ){
		//alert("not supported");
	} 

}

function getIEVersion(){
var ver = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
 var ua = navigator.userAgent;
 var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
 if (re.exec(ua) != null)
   ver = parseFloat( RegExp.$1 );
}
return ver;
}


function ieIndexFix(selector) {
        if(getIEVersion() > 0 && getIEVersion() < 8) {
                $(selector).parents().each(function() {
                        var p = $(this);
                        var pos = p.css("position");

                        if(pos == "relative" || pos == "absolute" || pos == "fixed") {
                                p.addClass("indexFix");
                        }
                });
        }
}

// see if browser is running in Windows high contrast mode
function highContrast() {
	if(BrowserDetect.browser == 'Safari' || BrowserDetect.OS == 'Apple'){return -1;}

	var a,b;
	a = document.createElement("div");
	a.style.color="rgb(31,41,59)";
	document.body.appendChild(a);
	b = document.defaultView ? document.defaultView.getComputedStyle(a,null).color : a.currentStyle.color;
	document.body.removeChild(a);
	b = b.replace(/ /g,"");
	return b != "rgb(31,41,59)";
}

function isHighContrast() { 
	return highContrast() === true;
}

// build an icon url from a service elem's class
function computeServiceIconUrl(jqObj) {
	var service = jqObj.attr('class').match(/([a-z]+)-service/);
	if(service && service.length > 1) {
		return '../img/favicons/'+ service[1] +'.png';
	} 
	return '';
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function browserCheck() {
	var doNotShow = (typeof browserCheckOptOut != "undefined") ? browserCheckOptOut: "yes";
	
	if (typeof doBrowserCheck == "undefined") {
		doBrowserCheck = false;
	}
	
	
	// If the user saw it, or its turned off in the config
	if ( doNotShow === "yes" || doBrowserCheck === false ) {
		return;
	}
	
	var showOldNotice = false;
	var showUnsupportedNotice = true;
	switch (BrowserDetect.browser.toLowerCase()) {
		case "firefox":
			showUnsupportedNotice = false;
			if ( BrowserDetect.version < minFF ) {
				showOldNotice = true;
			}
			break;
		case "explorer":
			showUnsupportedNotice = false;
			if ( BrowserDetect.version < minIE ) {
				showOldNotice = true;
			}
			break;
		case "safari":
			showUnsupportedNotice = false;
			if ( BrowserDetect.version < minSA) {
				showOldNotice = true;
			}
			break;
		case "chrome":
			showUnsupportedNotice = false;
			if ( BrowserDetect.version < minCH ) {
				showOldNotice = true;
			}
			break;
	}
	if ( showOldNotice === true ) {
		showBrowserNotice(BrowserDetect.browser, false);
	} else if ( showUnsupportedNotice === true ) {
		showBrowserNotice(BrowserDetect.browser, true);
	}
}

function showBrowserNotice(browserName, unsupported) {
	
	var title = [];
	if ( unsupported === true ) {
		title.push("<b>Whoa!<br/><br/> You're running a non-supported browser.</b><br/><br/>A number of websites, including this one, work better with newer browsers such as Firefox, Safari, Chrome, and Internet Explorer. ");
	} else {
		title.push("<b>Whoa!<br/><br/> You're running an old version of "+browserName+".</b><br/><br/>A number of websites, including this one, work better with newer versions of "+browserName+". ");
	}

	title.push("While you can still browse this site, not all features may be available to you. Consider upgrading your browser now for the best experience.<br/><br/>Here are some suggested browsers. They are faster, safer and absolutely free.<br/><br/>");

	var html = [];
	html.push("<style>.clear {clear:both;} </style>");
	html.push("<div id=\"browsercheck\">");
	html.push("<ul>");
	html.push("<li><span class=\"browserName\">Firefox</span><br/><a href=\""+FFdownloadURL+"\" target=\"_blank\"><img src=\"/img/browser/firefox.gif\" /></a></li>");
	html.push("<li><span class=\"browserName\">Safari</span><br/><a href=\""+SAdownloadURL+"\" target=\"_blank\"><img src=\"/img/browser/safari.gif\" /></a></li>");
	html.push("<li><span class=\"browserName\">Chrome</span><br/><a href=\""+CHdownloadURL+"\" target=\"_blank\"><img src=\"/img/browser/chrome.gif\" /></a></li>");
	if ( BrowserDetect.OS == 'Windows' ) {
		html.push("<li><span class=\"browserName\">Internet Explorer</span><br/><a href=\""+IEdownloadURL+"\" target=\"_blank\"><img src=\"/img/browser/ie.gif\" /></a></li>");
	} 
	html.push("</ul><div class=\"clear\"></div>");
	html.push("<form class=\"service-form none\" ><fieldset><div class=\"dialog-buttons\" style=\"text-align:right;\" ><button class=\"button ls_grey_bt reset\" onClick=\"popup.closePopup();\" type=\"reset\"><p class=\"bt_left\"></p><p class=\"bt_center\"><span class=\"bt_content\">No Thanks</span></p><p class=\"bt_right\"></p></button></div></fieldset></form></div>");

	popup.openPopup({closeCallback:browserCheckClosed});
	popup.setTitle(title.join(''));
	popup.setBody(html.join(''));
	$('select').hide();

	$('#_popup').addClass('browsercheck-dialog');
	if ( BrowserDetect.OS != 'Windows' ) {
		$("div#browsercheck").css("width","400px");
	}
	setDoNotShow();
}

function browserCheckClosed() {
	$('#_popup').removeClass('browsercheck-dialog');
	$('select').show();
}

function setDoNotShow() {
	$.getJSON('/settings/seen_browsercheck', 
		function(data) {
        	if (data.error) {
            	return;
         	} 
		}
	);
}





window.ls = window.ls||{};

ls.search = ls.search||{
	isTyping: false,
	searchType: "",
	hintText: "Search",
	
	activeTab: $(),
	
	form: $(),
	logos: $(),
	input: $(),
	button: $(),
	
	tabs: $(),
	tabList: $(),
	logoList: $(),
	typeHolder: $(),
	
	activeTab: $(),
	
	init: function(){
		ls.search.form = $("#ls-headerSearch");
		ls.search.logos = $(".ls-headerSearch-logos").eq(0);
		ls.search.input = $(".ls-headerSearch-text").eq(0);
		ls.search.button = $(".ls-headerSearch-button").eq(0);
		
		ls.search.tabs = $(".ls-headerSearch-tabs");
		ls.search.tabList = ls.search.tabs.find(".ls-headerSearch-tab");
		ls.search.logoList = $(".ls-headerSearch-logo");
		ls.search.typeHolder = ls.search.tabs.children("input").eq(0);
		
		ls.search.searchType = ls.search.typeHolder.val();
		ls.search.activeTab = ls.search.tabs.find(".active");

		ls.search.initSearchBox();
		ls.search.initTabs();
	},
	
	
	setHint: function(){
		var mustUpdate = ( ls.search.input.val() == ls.search.hintText );
		
		ls.search.hintText = "Search " + ls.search.searchType;
		
		if(mustUpdate) ls.search.setToHint();
	},
	
	setToHint: function(){
		ls.search.input.val(ls.search.hintText);
	},
	// TODO: separate hint text from default value
	
	isBlank: function(){
		return $.trim(ls.search.input.val()) == "";
	},
	
	isHint: function(){
		return ls.search.input.val() == ls.search.hintText;
	},
	
	isInactive: function(){
		return ls.search.isHint() && !ls.search.input.hasClass("typing");
	},
	
	isGivenQuery: function(){
		return !ls.search.isBlank() && $("#ls-headerSearch-queryGiven").val() == ls.search.input.val();
	},
	
	setTypingState: function( val ){
		if( val ){
			ls.search.isTyping = true;
			ls.search.input.addClass( "typing" );
			ls.search.logos.addClass( "typing" );
		} else {
			ls.search.isTyping = false;
			ls.search.input.attr( "class", "ls-headerSearch-text" );
			ls.search.logos.attr( "class", "ls-headerSearch-logos" );
		}
	},
	
	beginTyping: function(){
		ls.search.setTypingState( true );
	},
	
	searchBoxClick: function(){
		if( ls.search.isInactive() ) ls.search.input.val("");
		ls.search.beginTyping();
	},
	
	searchBoxLogosClick: function(){
		ls.search.searchBoxClick();
		ls.search.input.focus();
	},
	
	searchBoxUnclick: function(){
		if( ls.search.isBlank() ){
			ls.search.setTypingState(false);
			ls.search.setToHint();
		}
	},

	submitSearch: function(){
		var submitSearchType = function(){
			var name = ls.search.searchType.toLowerCase();
			ls.search.typeHolder.attr("name", name);
			ls.search.typeHolder.val( "true" );
			if( name == "lifestream" || name == "everything" ){
				ls.search.typeHolder.remove();
			}
		};
		
		if( ls.search.isInactive() || ls.search.isBlank() ) {
			console.debug("trying to submit a default search, cancelling...");
			return false;
		}

		submitSearchType();

		try { reportStats("LSTW:SearchResults"); } catch(e){
			console.error("ls.search.submitSearch() failed to reportStats('LSTW:SearchResults')");
		};
	},
	
	initSearchBox: function(){
		// searchType will be wrong initially
		ls.search.findSearchType();
		// the FTL hint is going to be wrong initially
		ls.search.setHint();
		
		// if it's already been written in, simulate a click to catch up our state machine
		if( !ls.search.isGivenQuery() && !ls.search.isHint() ) ls.search.searchBoxClick();
			
		// find whether the icons should be active based on the current active tab (from FTL)
		if( ls.search.activeTab.find("a").html() == "Everything" ){
			ls.search.setIconsAll();
		} else { // for now, People / Places --> only lifestream icon
			ls.search.setIconsSingle( "ls" );
		}
		
		// register events
		ls.search.input.focus( ls.search.searchBoxClick );
		ls.search.logos.click( ls.search.searchBoxLogosClick );

		ls.search.input.blur( ls.search.searchBoxUnclick );
		ls.search.form.submit( ls.search.submitSearch );

		try {
			// since our jQuery events are registered, we can disable the temporary while-loading clear function
			ls.search.input.get(0).onclick = "";
		} catch (e) {
			// handle if there is no search box!
		}
	},
	
	setIconsSingle: function( key ){
		ls.search.logoList.each(function(){
			if( $(this).hasClass(key) ){
				$(this).removeClass("hidden");
			} else {
				$(this).addClass("hidden");
			}
		});
	},
	
	setIconsAll: function(){
		ls.search.logoList.removeClass("hidden");
	},
	
	setIconsFromSearchType: function(){
		if( ls.search.searchType == "Everything" ) {
			ls.search.setIconsAll();
		} else {
			ls.search.setIconsSingle("ls");
		}
	},

	// in case we want to keep this in an input as we're going rather than processing onSubmit
	setSearchType: function(newType){
		ls.search.searchType = newType;
	},
	
	findSearchType: function(){
		ls.search.setSearchType( ls.search.findActiveTabText() );
	},
	
	findActiveTabText: function(){
		return ls.search.activeTab.children("a").eq(0).html();
	},
	
	setTabActive: function( tabElement ){
		tabElement = $(tabElement);

		ls.search.activeTab.removeClass("active");
		tabElement.addClass("active");
		ls.search.activeTab = tabElement;
		
		ls.search.findSearchType();
		ls.search.setIconsFromSearchType();
		ls.search.setHint();
	},
	
	clickTab: function(){
		ls.search.setTabActive($(this));
		
		if( !ls.search.isInactive() ){
			ls.search.form.submit();
		}

		return false;
	},
	
	initTabs: function(){
		ls.search.tabList.click( ls.search.clickTab );
	}
};

$( function(){
	ls.search.init();
});





function AsnsSignIn( obj, leftOffSet, topOffSet ) {
    var pSNS = document.getElementById("snsMiniUI");
    pSNS.innerHTML = "";
    pSNS.innerHTML += _sns_var_;
    /*
     * This code seems to be breaking WAOL 9.5. Since we pass
     * in 0, 0 as the offsets, it doesnt really change any positioning
     * If there is a use case where this is needed, I can't find it.
     * Not removing in case we need to find another workaround.
    if ( document.all ) {
        //var pos = findPos(obj);
        //pSNS.style.position = 'absolute';
        //pSNS.style.left = (pos[0] + leftOffSet - 900) + 'px';
        //pSNS.style.top =  (pos[1] + topOffSet - 150)  + 'px';
    } else {
        obj.appendChild(pSNS);
        pSNS.style.left = leftOffSet + 'px';
        pSNS.style.top =  topOffSet  + 'px';
        pSNS.style.position = 'relative';
    }
    pSNS.style.zIndex = 5000;
    pSNS.style.display = "block";
    */
}

/* Google Chrome Extension Promo */
$(document).ready( function() {
	setTimeout( function() {
		var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
		var is_authed = ( !(typeof WIM === "undefined") && WIM.aimId != '' );
		if ( is_authed && is_chrome && localStorage.getItem('chrome-extension-promo') != 1 ) {
			var promo = $('<div id="chrome-extension-promo"></div>');
			var span = $('<span>Get the AOL Lifestream Google Chrome Extension: stay in the loop while you browse the web!</span>');
			var install = $('<a target="_blank" class="install" href="https://chrome.google.com/extensions/detail/cnabicdoplelkdcpdiodoodgdebaolcn">Install</a>');
			install.click( function() { 
				localStorage.setItem('chrome-extension-promo',1);
				$('#chrome-extension-promo').slideUp('slow');
				reportStats('LSTW:installchrome');
				return true;
			});
			var close = $('<a class="close" href="#">X</a>');
			close.click( function() {
				localStorage.setItem('chrome-extension-promo',1);
				$('#chrome-extension-promo').slideUp('slow');
				reportStats('LSTW:closechrome');
				return false;
			});
			promo.append(close).append(install).append(span);
			$('body').prepend(promo);
			$('#chrome-extension-promo').slideDown('slow');
		}
	}, 50 ); // Give the WIM document.ready time to run, we need WIM.aimId if they are logged in. :(
});
/* End Google Chrome Extension Promo */
/* Slider Promo Code for New Unauth Landing page */
$(document).ready(function() {
	// Handle the slides
	var promoTimeoutId = -1;
	var promoTotal = 3;
	var promoNum = 0;
	var promoSliderTimeoutMs = 8000;
	var promoSliderTransitionMs = 500;
	var promoSliderPaused = false;
	
	var showPromo = function(num,callback) {
		var leftVal = -(num - 1) * 940;
		$('#landingPromoControls li.control').removeClass('active');
		var title = $($('#landingPromoControls li.control').get(num-1)).addClass('active').find('a').attr('title');
		$('#landingPromoControls li.title').text(title);
		$('#landingPromoContainer').animate( { left : leftVal }, promoSliderTransitionMs, 'swing', callback );
	};
	var promoSlider = function() {
		if ( promoSliderPaused ) {
			promoTimeoutId = setTimeout(promoSlider,50);
			return;
		}
	    promoTimeoutId = -1;
		promoNum++;
		if ( promoNum > promoTotal ) {
			promoNum = 1;
		}
		showPromo(promoNum, function(){
			promoTimeoutId = setTimeout(promoSlider,promoSliderTimeoutMs);
		});
	};
	$('#landingPromoControls li a').each( function(idx,el) {
		$(el).click( function() {
			if ( promoTimeoutId > 0 ) {
				clearTimeout(promoTimeoutId);
			}
			showPromo(idx + 1);
			return false;
		});
	});
	$('#landingPromo')
		.bind("mouseenter",function(){ promoSliderPaused = true; })
		.bind("mouseleave",function(){ promoSliderPaused = false; });
	promoSlider();
	
});
/* End Slider Promo Code */
/* Reparent our dialogs so overaly's work */
$(document).ready( function() {
	var body = $('body');
	$('#landing #signInDialog').appendTo(body);
	$('#landing #signUpDialog').appendTo(body);
});
/* End Reparent code */
