try{document.execCommand("BackgroundImageCache", false, true); } catch(e) {}
(function($){
	// setting var undefined like this allows you to do this:
	// if (blah == undefined) ...
	// instead of
	// if (typeof blah == 'undefined') ...
	var undefined;
	$.Comments = function(options){
					var self = this;
					this.defaults = {
						links: $('a.commentsLink'),
						lessLinks: $('a.lessCommentsLink'),
						lastLinks: $('a.lastCommentsLink'),
						pageBy:3,
						ajaxURL: '/svc/ObjectModelService.svc/GetCommentsHTML'
					};
					
					this.settings = $.extend({}, this.defaults, options);
					this.commentLinks = this.settings.links;
					
					function _init(){
						
						self.settings.links.each(function() {
							$(this).attr('commentcount', '2');
							var countHint = $(this).parents('.question-container').attr('counthint');
							if(countHint == 0 || countHint == 1)
								_disable($(this));
						});
						
						self.settings.lessLinks.each(function() {
							_disable($(this));
						});
						
						self.settings.lastLinks.each(function() {
							_disable($(this));
						});
						
						self.moreLinks(self.settings.links);
						
						
						self.settings.lessLinks.bind('click', function() {
							var thisLink = $(this);
							var $questionContainer = thisLink.parents('.question-container');
							var $moreLink = $questionContainer.find('p a.commentsLink');
							var $lastLink = $questionContainer.find('p a.lastCommentsLink');
							var commentCount =  $moreLink.attr('commentcount');
							
							thisLink.commentCount = parseInt(commentCount);
							
							var $questionContainer = thisLink.parents('.question-container');
							var $commentsHTML = $questionContainer.find('.comments-list .more-comments');
							var $scrollToMe = $questionContainer.find('.comments-list div.scrollTo');
							
							var ajaxURL = self.settings.ajaxURL + '?videoID=' + $questionContainer.attr('id') + '&startIndex=' + thisLink.commentCount + '&numToRetrieve=50';
							
							if((commentCount < (self.settings.pageBy + 2)) && (commentCount != 2)) {
								$commentsHTML.slideUp('slow', function() {
									$commentsHTML.empty();
									_scrollToMe($scrollToMe);
									$questionContainer.removeClass('open');
									jQuery.each(jQuery.browser, function(i, val) {
									  if(i=="msie" && jQuery.browser.version.substr(0,1)=="6") {
										 var $questionBottom = $questionContainer.find('.question-bottom');
										 if($questionBottom.hasClass('ie-bottom') == true)
											$questionBottom.removeClass('ie-bottom')
									  }
									});
								});	
								thisLink.commentCount = 2;
								$moreLink.attr('commentcount', thisLink.commentCount);
								$moreLink.text('More Comments');
								_enable($moreLink);
								_disable($lastLink);
								_disable(thisLink);
							} else if(commentCount != 2) {
								var whichChild = commentCount - (self.settings.pageBy + 2);
								if(whichChild > 0) {
									$commentsHTML.find('div:nth-child('+ whichChild + ')').attr('id','removeStartingHere');
									var wrapDiv = document.createElement("div");
									$wrapDiv = $(wrapDiv);
									$wrapDiv.attr('id', 'removeMe');
									$('#removeStartingHere ~ div').wrapAll($wrapDiv);
									$('#removeMe').slideUp('slow', function() {
										$('#removeMe').empty();
										_scrollToMe($scrollToMe);
										thisLink.commentCount -= self.settings.pageBy;
										$('#removeMe').remove();
										$moreLink.attr('commentcount', thisLink.commentCount);
										$moreLink.text('More Comments');
										_enable($moreLink);
										$('#removeStartingHere').attr('id', '');
									});
								} else {
									$commentsHTML.slideUp('slow', function() {
										$commentsHTML.empty();
										_scrollToMe($scrollToMe);
										$questionContainer.removeClass('open');
										jQuery.each(jQuery.browser, function(i, val) {
										  if(i=="msie" && jQuery.browser.version.substr(0,1)=="6") {
											 var $questionBottom = $questionContainer.find('.question-bottom');
											 if($questionBottom.hasClass('ie-bottom') == true)
												$questionBottom.removeClass('ie-bottom')
										  }
										});
									});	
									thisLink.commentCount = 2;
									$moreLink.attr('commentcount', thisLink.commentCount);
									$moreLink.text('More Comments');
									_enable($moreLink);
									_disable(thisLink);
									_disable($lastLink);
								}
							}
							
						});
						
						self.settings.lastLinks.bind('click', function(e) {
							var thisLink = $(this);
							var $questionContainer = thisLink.parents('.question-container');
							var $moreLink = $questionContainer.find('p a.commentsLink');
							var $lessLink = $questionContainer.find('p a.lessCommentsLink');
							var commentCount =  $moreLink.attr('commentcount');
							
							thisLink.commentCount = parseInt(commentCount);
							
							var $questionContainer = thisLink.parents('.question-container');
							var $commentsHTML = $questionContainer.find('.comments-list .more-comments');
							var $scrollToMe = $questionContainer.find('.comments-list div.scrollTo');
							if(commentCount != 2) {
								$commentsHTML.slideUp('slow', function() {
										$commentsHTML.empty();
										_scrollToMe($scrollToMe);
										$questionContainer.removeClass('open');
										_disable(thisLink);
										_disable($lessLink);
										jQuery.each(jQuery.browser, function(i, val) {
										  if(i=="msie" && jQuery.browser.version.substr(0,1)=="6") {
											 var $questionBottom = $questionContainer.find('.question-bottom');
											 if($questionBottom.hasClass('ie-bottom') == true)
												$questionBottom.removeClass('ie-bottom')
										  }
										});
										_enable($moreLink);
								});	
							}
							
							thisLink.commentCount = 2;
							$moreLink.attr('commentcount', thisLink.commentCount);
							$moreLink.text('More Comments');
						});
						
						if (self.init != undefined) self.init();
					};
					
					// start:private
					function _scrollToMe(obj){
						$.scrollTo(obj, 400);
					}
					
					function _disable(obj) {
						obj.css('color', 'gray');
						obj.css('text-decoration', 'none');
						obj.css('opacity', '.6');
						obj.css('cursor', 'default');
					}
					
					function _enable(obj) {
						obj.css('color', '#E7262A');
						obj.css('text-decoration', 'underline');
						obj.css('opacity', '1');
						obj.css('cursor', 'pointer');
					}
					
					// end:private
					
					this.moreLinks = function(links) {
						links.bind('click', function() {
							var thisLink = $(this);
							thisLink.commentCount = thisLink.attr('commentcount');
							thisLink.commentUpperBound = thisLink.parents('.question-container').attr('counthint');
							thisLink.commentCount = parseInt(thisLink.commentCount);
							
							var $questionContainer = thisLink.parents('.question-container');
							var $commentsHTML = $questionContainer.find('.comments-list .more-comments');
							var $scrollToMe = $questionContainer.find('.comments-list div.scrollTo');
							var $lessLink = $questionContainer.find('p a.lessCommentsLink');
							var $lastLink = $questionContainer.find('p a.lastCommentsLink');
							
							var ajaxURL = self.settings.ajaxURL + '?videoID=' + $questionContainer.attr('id') + '&startIndex=' + thisLink.commentCount + '&numToRetrieve=' + self.settings.pageBy;
							
							thisLink.unbind('click');
							
							$.ajax({
							  url: ajaxURL,
							  cache: false,
							  success: function(html){
									$commentsHTML.append(html);
									if(html == '') {
										self.moreLinks(links);
									}
									else {
										$commentsHTML.slideDown('slow', function() {	
											_scrollToMe($scrollToMe);
											jQuery.each(jQuery.browser, function(i, val) {
											  if(i=="msie" && jQuery.browser.version.substr(0,1)=="6") {
												 var $questionBottom = $questionContainer.find('.question-bottom');
												 if($questionBottom.hasClass('ie-bottom') == false)
												 	$questionBottom.addClass('ie-bottom')
											  }
											});

										});

										$questionContainer.addClass('open');

										if((thisLink.commentCount + 1) >= thisLink.commentUpperBound){
											_disable(thisLink);
										}
										thisLink.commentCount += self.settings.pageBy;
										thisLink.attr('commentcount', thisLink.commentCount);
										_enable($lessLink);
										_enable($lastLink);
										self.moreLinks(links);
									}	
									
							  },
							  error: function(html) {
								  self.moreLinks(links);
							  }
							});
							
							thisLink.attr('commentcount', thisLink.commentCount);
						});
					}
						
					_init();
	};
	
$.PopUp = function(options){
					var self = this;
					this.defaults = {
						innerHtml: '<div class="form-container"><form id="question-form" class="questionForm" action="javascript:void(0)"><ul><li id="topic"><label for="questionText">Enter your thought, question, concern, or story here.</label></li><li id="question"><div class="text-bg left"><textarea id="questionText"></textarea></div></li><li><a href="javascript:void(0)" id="question-form-submit" class="submit"><img src="/img/button-submit-tio.gif" width="50" height="20" border="0" alt="Submit" title="Submit" /></a></li></ul></form></div><a href="javascript:void(0)" class="close"><img src="/img/button-close-tio.gif" width="18" height="18" border="0" alt="Close" title="Close" /></a>',
						trigger:null,
						modal:null
					};
					
					this.settings = $.extend({}, this.defaults, options);
					
					function _init(){
						var div = document.createElement('div');
						var $div = $(div);
						
						$div.addClass('overlay');
						$div.attr('id', self.settings.id);
						$div.selfOpen = 0;
						var html = '<div class="overlay-content">' + self.settings.innerHtml + '</div>';
						$div.html(html);

						self.div = $div;	
						
						
						if(self.settings.trigger) {
							self.settings.trigger.bind('click', function() {
								var position = new Array;
								position = _findPos(self.settings.position.get(0));
								var x = position[0];
								var y = position[1];
								
								_destroyYouTubePopUp();
								self.div.find('textarea').val('');
								
								if(!$('#' + self.settings.id).get(0)) {
									$('body').append($div);
									var submitTrigger = $div.find('.submit');
									submitTrigger.bind('click', function(e) {
										var theForm = $(this).parents('form');
										if(theForm.hasClass('commentForm')) {
											var id = theForm.attr('video');
											var text = theForm.find('textarea').val();
											
											text = _stripHTML(text);
											text = _replaceDQuotes(text);
											text = $.trim(text);
											
											if(text == '')
												return false;
											var postMe = '{"videoID":"' + id + '","commentText":"' + text + '"}';
											
											theForm.find('textarea').val('Sending comment...');
											$(this).unbind('click');					
											
											if(self.settings.isLoggedIn) {
												 $.ajax({
												   type: "POST",
												   url: self.settings.service,
												   data: postMe,
												   dataType:"json",
												   contentType: "application/json;charset=utf-8",
												   success: function(data){
													 if(data.d.Success) {
														theForm.remove();
														var successHTML = '<div class="message">Thank you. Your comment has been posted!</div>';
														self.div.find('.form-container').html(successHTML);
														//self.div.remove();
													 }
													 else {
														theForm.remove();
														var failHTML = '<div class="message">Your comment could not be posted. ' + data.d.ErrorMessage + '</div>';
														self.div.find('.form-container').html(failHTML);
													 	//self.div.remove();
													 }
												   },
												   error: function(data){
													   	theForm.remove();
													   	var failHTML = '<div class="message">Your comment could not be posted at this time.</div>';
														self.div.find('.form-container').html(failHTML);
												   }
												 });
											} else {
												var youTubePosition = new Array;
												youTubePosition = _findPos(self.settings.position.get(0));
												self.hide();
												if(self.settings.modal)
													$('#modal').remove();
												_creatYouTubePopup(youTubePosition, text, id, self.settings.youTubeSignInUrl);
											}
		
										} else if(theForm.hasClass('questionForm')) {
											var topicName = "Something has been sumbitted.";
											//var topicName = theForm.find('input#topicName').val();
											var questionText = theForm.find('textarea').val();
											
											if(topicName == '')
												return false;
												
											if(questionText == '')
												return false;
											
											//topicName = _stripHTML(topicName);
											//topicName = _replaceDQuotes(topicName);
											//topicName = $.trim(topicName);
											
											
											
											questionText = _stripHTML(questionText);
											questionText = _replaceDQuotes(questionText);
											questionText = $.trim(questionText);
											
											var postMe = '{"topic":"' + topicName + '","question":"' + questionText + '"}';
											
											theForm.find('textarea').val('Sending Question...');
											
											$.ajax({
												   type: "POST",
												   url: self.settings.service,
												   data: postMe,
												   dataType:"json",
												   contentType: "application/json;charset=utf-8",
												   success: function(data){
													 if(data.d.Success) {
														var successHTML = '<div class="message">Thank you. Your submission has been accepted! Come back soon to see if has been approved and posted.</div>';
														self.div.find('.form-container').html(successHTML);
													 }
													 else {
													   	var failHTML = '<div class="message">Your question could not be sent at this time.</div>';
														self.div.find('.form-container').html(failHTML);
													 }
												   },
												   error: function(data){
													   
												   }
												 });
										}
									});
								}
								
								if(self.settings.modal) {
									var modalDiv = document.createElement('div');
									var $modalDiv = $(modalDiv);
									
									$modalDiv.attr('id', 'modal');
									var html = '<iframe frameborder="0" />';
									$modalDiv.html(html);
									$modalDiv.css('display', 'none');
			
									self.modal = $modalDiv;
									$('body').append(self.modal);
									self.modal.add(".modal iframe").css({height: $(document).height()});
									self.modal.show();
								}
								
								var checkForm = self.div.find('form');
								if(checkForm.hasClass('commentForm'))  {
									$div.css('left', (x-300));
								} else {
									$div.css('left', x);
								}
								
								$div.css('top', y);
								$div.selfOpen = 1;
								
								var closeButton = self.div.find('.close');
								closeButton.click(function(e) {
									e.preventDefault();
									self.removeMe();
									self.div.selfOpen = 0;
									if(self.settings.modal)
										$('#modal').remove();
								});
								
							});
							
							//no longer necessary as every popup has a modal blocker
							/*$(document).click(function(e){  
								var triggerID = self.settings.trigger.attr('id');
								var targetID = $(e.target).attr('id');
								if(triggerID != targetID) {
									if(self.div.selfOpen) {				   
										var parent = '#' + self.div.attr('id');
										if(!$(e.target).parents(parent).get(0)) {
											//self.hide();
											self.div.selfOpen = 0;
											self.div.remove();
											var html = '<div class="overlay-content">' + self.settings.innerHtml + '</div>';
											self.div.html(html);
											if(self.settings.modal)
												$('#modal').remove();
										}
									}
								}
							});*/					
						}
						else {
							if(!$('#' + self.settings.id).get(0))
								$('body').append($div);		
						}

						if (self.init != undefined) self.init();
					};
					
					// start:private
					function _private(){
						
					}
					
					function _creatYouTubePopup(position, commentText, videoID, nextLocation) {
						var html = '<div id="divYouTubePopup" class="youtube-popup"><div style="position: relative; float: left;"><div class="youtube-popup-bg"><p>You\'ll be briefly redirected to YouTube to log in or create an account before you post your comment. Then you\'ll be sent right back. Sorry for the inconvenience.</p><ul><li><a id="ancYouTubeLoginDecline" href="#"><img height="25" width="96" border="0" title="no thanks" alt="no thanks" src="img/popup-nothanks.gif"/></a></li><li><a id="ancYouTubeLoginAccept" href="#"><img height="26" width="31" border="0" title="OK" alt="OK" src="img/popup-ok.gif"/></a></li></ul></div></div></div>';
						var youTubeLogin = new $.PopUp({id:"youtubeLogIn",innerHtml:html,modal:true});
						youTubeLogin.show(position);
						
						var youTubeDecline = $('#ancYouTubeLoginDecline');
						var youTubeAccept = $('#ancYouTubeLoginAccept');
						
						youTubeDecline.bind('click', function() {
							$('#modal').remove();
							$('#youtubeLogIn').remove();
							self.removeMe();
						});
						
						youTubeAccept.bind('click', function() {
							/*** logic taken from roufa's AdCouncliClasses.js***/
							var pathEscaped = _safeEscape(location.pathname);
							var insertText = pathEscaped + _safeEscape("?commentText_" + videoID + "=" +  _safeEscape(commentText));
							// Option 1: the path has a qs, so it ends with an encoded '?'.
							var pathWithQuestionMark = pathEscaped + _safeEscape("?");
							if (nextLocation.indexOf(pathWithQuestionMark) > -1) {
								nextLocation = nextLocation.replace(pathWithQuestionMark, insertText + _safeEscape("&"));
							}
							// Option 2: the path has no qs, so it ends with an UNENCODED '&'.
							else if (nextLocation.indexOf(pathEncoded + "&") > -1) {
								nextLocation = nextLocation.replace(pathEscaped + "&", insertText + "&");
							}

        					location.href = nextLocation;
						});
						
					}
					
					function _destroyYouTubePopUp() {
						if($('#youtubeLogIn').get(0)) {
							$('#youtubeLogIn').remove();
						}
					}
					
					function _findPos(obj) {
						var curleft = curtop = 0;
						if (obj.offsetParent) {
							curleft = obj.offsetLeft
							curtop = obj.offsetTop
					
							while (obj = obj.offsetParent) {
								curleft += obj.offsetLeft
								curtop += obj.offsetTop
							}
						}
						return [curleft,curtop];
					}
					
					function _safeEscape(str) {
						/***from roufa's AdCouncilClasses.js***/
						var output = encodeURIComponent(str);
						// encodeURIComponent doesn't handle these characters that escape will: ~!()'
						output = output.replace(/\~/g, escape('~'));
						output = output.replace(/\!/g, escape('!'));
						output = output.replace(/\(/g, escape('('));
						output = output.replace(/\)/g, escape(')'));
						output = output.replace(/\'/g, escape("'"));
						// Nothing handles the asterisk.
						output = output.replace(/\*/g, '%2A');
						return output;	
					}
					
					function _replaceDQuotes(str) {
						str = str.replace(/\"/g, '\\"');
						str = str.replace(/[\n\r\t]/g, '\\n');
						return str;
					}
					
					function _stripHTML(str) {
						str = str.replace(/<(?:.|\s)*?>/g, '');
						return str;
					}
					// end:private
					
					// start:public
					
					this.show = function(position) {
						
						if(self.settings.modal) {
							var modalDiv = document.createElement('div');
							var $modalDiv = $(modalDiv);
							
							$modalDiv.attr('id', 'modal');
							var html = '<iframe frameborder="0" />';
							$modalDiv.html(html);
							$modalDiv.css('display', 'none');
	
							self.modal = $modalDiv;
							$('body').append(self.modal);
							self.modal.add(".modal iframe").css({height: $(document).height()});
							self.modal.show();
						}
						
						var x = position[0];
						var y = position[1];
						self.div.css('left', x);
						self.div.css('top', y);
						self.div.selfOpen = 1;
					}
					
					this.hide = function () {
						self.div.css('left', '-9999px');	
					}
					
					this.removeMe = function() {
						self.div.remove();
						var html = '<div class="overlay-content">' + self.settings.innerHtml + '</div>';
						self.div.html(html);
					}
					// end:public		
					_init();
	};
	
$.commentOverlays = function(options){
					var self = this;
					this.defaults = {
						questionContainers : $('.question-container'),
						ajaxURL: '/svc/ObjectModelService.svc/PostComment'
					};
					
					this.settings = $.extend({}, this.defaults, options);
					
					function _init(){
						/*** un comment this and below if statement to enable direct commenting after youtube login
						/*var url = location.href;
						
						if(url.indexOf("commentText") != -1) {
							var urlArray = url.split("?");	
							url = urlArray[1];
							urlArray = url.split("&");
							url = urlArray[0];
							urlArray = url.split("=");
							var commentID = urlArray[0];
							commentID = commentID.slice(12);
							var commentText = urlArray[1];
						}*/
						
						self.settings.questionContainers.each(function() {
							var questionContainer = $(this);		
							var $commentsButton = questionContainer.find('.comment-button');
							var overlayId = questionContainer.attr('id') + '-comments-overlay';
							var html = '<div class="form-container commentPopUp"><form class="commentForm" id="comment-form-' + questionContainer.attr('id') +  '" video="' + questionContainer.attr('id') + '"><ul><li><span>Comment</span><textarea></textarea></li><li><a href="javascript:void(0)" class="submit" id="comment-form-submit-' + questionContainer.attr('id') +  '"><img src="/img/button-submit-tio.gif" width="50" height="20" border="0" alt="Submit" title="Submit" /></a></li></ul></form></div><a href="javascript:void(0)" class="close"><img src="/img/button-close-tio.gif" width="18" height="18" border="0" alt="Close" title="Close" /></a>';
							new $.PopUp({id:overlayId,trigger:$commentsButton,position:$commentsButton,innerHtml:html,service:self.settings.ajaxURL,isLoggedIn:self.settings.isLoggedIn,youTubeSignInUrl:self.settings.youTubeSignInUrl,modal:true});
							
							/*if(commentID == questionContainer.attr('id')) {
								$commentsButton.trigger('click');
								var $textField = $('.form-container textarea');
								commentText = unescape(commentText);
								commentText = commentText.replace(/\+/g, '\ ');
								$textField.val(commentText);
								$('.form-container .submit').trigger('click');
							}*/
							
						});
						if (self.init != undefined) self.init();
					};

					_init();
	};
	
$.submitSomethings = function(options) {
	var self = this;
	this.defaults = {
		questionContainers : $('.question-container'),
		ajaxURL: '/svc/ObjectModelService.svc/EmailQuestionSubmission'
	};
	
	this.settings = $.extend({}, this.defaults, options);
	
	function _init() {
		
		self.settings.questionContainers.each(function() {
			var questionContainer = $(this);
			var $sumbitSomethingButton = questionContainer.find('.question-button');
			var overlayId = 'submit-question-overlay';
			var $position = questionContainer.find('.commentsLink');
			
			new $.PopUp({id:overlayId,trigger:$sumbitSomethingButton,position:$position,service:self.settings.ajaxURL,modal:true});
		});
		
		if (self.init != undefined) self.init();
	};
	
	_init();
};
	
})(jQuery);