/*
 * Computerworld twitter
 */

(function($) {
	var twKeyword = "cso",	// search keyword
	numTweets = 4,	// number of tweets to retrieve
	commentsType = "page", // page or overlay?
	taxonomyid = 0,	// taxonomy ID, for ads
	loadAds = 0,	// load ads or not, depending on sponsorship
		
	twitterTableID = "tweetlist", // ID of the table where the tweets should live
	parentdiv = "twitter_module", // ID of Twitter div
	badWordsList = "asshole, ass,beaner,bitch,bollocks,bollox,boner,bullshit,chinc,clit ,cock,coon,cum,cunt,dildo,douche,fag,fuck,homo ,jizz,kunt,lesbo,nigga,nigger,penis,piss,pussy,queef,shit,sass,vagina";

	$.cwtwitter = {
		init: function(params) {
			twKeyword=params.keyword;
			numTweets=params.numTweets;
			commentsType=params.commentsType;
			taxonomyid = params.taxonomy;
			loadAds = params.sponsored;

			$.cwtwitter.getTweets({numTweets:numTweets,commentsType:commentsType});
		},

		getTweets: function(params){
			numTweets = params.numTweets;
			commentsType = params.commentsType;
			if(commentsType == "overlay") parentdiv = "twitter_app";
			else parentdiv = "twitter_module";
			
			var reqURL = "http://search.twitter.com/search.json?q="+twKeyword+"&rpp="+numTweets+"&lang=all&callback=?";
			$.ajax({
				url: reqURL,
				type: 'GET',
				// jsonp (vs json) automatically adds callback
				dataType: 'jsonp',
				timeout: 1000,
				error: function(e){ 
					writeFailWhale();
				},
				success: function(j){
					// if there are results
					if(j.results != '') {
						$('#'+parentdiv+' #first-tweet').hide();
						$('#'+parentdiv+' h3.update')
							.text("On Twitter now")
							.show();
						$('#'+parentdiv+' h4.tag')
							.show();
						// write the tweets
						$.each(j.results,function(i,twitterItem) {
							$.cwtwitter.writeTweet(twitterItem);
						});
						// module bottom link & button
						if(commentsType == "page"){
							$('table#tweetlist').after("<div class=\"more-tweets\"><a>More Tweets</a></div>");
							$('div.more-tweets').after("<div class=\"launch-btn\"><button id=\"add-tweet\">Add your "+twKeyword+" tweet</button></div>");
							
							// on click: open overlay and click tracking
							$('#'+parentdiv+' #add-tweet')
								.click(function() {
									$.cwtwitter.openOverlay();
									setClickTrackingVars('twitter_unexpanded_addtweets - onclick',this);
								});
							$('#'+parentdiv+' div.more-tweets')
								.click(function() {
									$.cwtwitter.openOverlay();
									setClickTrackingVars('twitter_unexpanded_moretweets - onclick',this);
								});
							$('#'+parentdiv+' h4.tag')
								.click(function() {
									$.cwtwitter.openOverlay();
								});
						}
						if(commentsType == "overlay"){
							$('#'+parentdiv+' #content .left').show();
							$('a.reply')
								.bind("click", function (){
									var thisTwClasses = $(this).attr('class');
									var thisTwNum = $.trim(thisTwClasses.replace("reply",""));
									var thisTwReply = '@'+$('span.username.'+thisTwNum).text();
									var enteredStatus = $('#status').val();
									$('#what_thinking').text("Your reply");
									$('#status').val(thisTwReply+" "+enteredStatus);
									$.cwtwitter.countChars();
									$('.tweetsent').hide();
									$('a.cancel').show();
							});
						}
					}
					else{
						$('#'+parentdiv+' h4.tag').hide();
						$('#'+parentdiv+' h3.update').text("Be the first to tweet on "+twKeyword);
						// write 'Sign in with Twitter' content
						$.cwtwitter.writeNoTweets();
					}
					// make all links target new window
					$('#'+parentdiv+' a').attr("target","_blank");
				}
			});
		},
		
		writeTweet: function(item){
			if (item.text != null) {
				if(!$.cwtwitter.isBadTweet(item.text)){
					var tweetID = item.id;
					var createdDate = new Date(item.created_at);
					var tweetTimestamp = prettyDate(createdDate);
					var tweetLink =  "http://twitter.com/"+item.from_user+"/status/"+tweetID;  
					var formattedSource = $.cwtwitter.formatSource(item.source);
					var formattedText = $.cwtwitter.addTweetLinks(item.text);
					var userImgHTML = "<td><div class=\"profile-pic\"><a href=\"http://www.twitter.com/"+item.from_user+"\"><img src=\""+item.profile_image_url+"\" width=48 height=48 alt=\""+item.from_user+"\" class=\"photo\" /></a></div></td>";                          
					var userNameHTML = "<span class=\"username\"><a title=\"\" class=\"screen-name\" href=\"http://www.twitter.com/"+item.from_user+"\">"+item.from_user+"</a></span>";
					var sourceHTML = "<span class=\"source-meta\"><a href=\""+tweetLink+"\">"+tweetTimestamp+"</a> from "+formattedSource+"</span>";
					var statusHTML = "<span class=\"status-body\">"+formattedText+"</span>";
					var fullTweetHTML= userImgHTML+"<td><div class=\"dialog\"><div class=\"content\"><div class=\"pointer\"></div><div class=\"t\"></div><span class=\"entry-meta\">"+userNameHTML+sourceHTML+"</span>"+statusHTML+"</div><div class=\"b\"><div></div></div></div></td>";
					
					$('<tr></tr>')
						.html(fullTweetHTML)  
						.attr('id', 'twtr'+tweetID)
						.addClass('tw'+tweetID)
						.appendTo('#'+parentdiv+' #'+twitterTableID);
					
					// if on overlay, add reply and retweet options
					if(commentsType == "overlay") {
					$('#'+parentdiv+' tr#twtr'+tweetID+' span.source-meta')
						.append('<a class=\"reply\">Reply</a>');
					
					$('#'+parentdiv+' tr#twtr'+tweetID+' span.username, #'+parentdiv+' tr#twtr'+tweetID+' a.reply, #'+parentdiv+' tr#twtr'+tweetID+' span.status-body')
						.addClass('tw'+tweetID);
					}
				}
			}
		},
		
		formatSource: function(tweetSource){
			var thisSource = tweetSource.replace(/&quot;/g,"\"");
			thisSource = thisSource.replace(/&lt;/g,"<");
			thisSource = thisSource.replace(/&gt;/g,">");
			return thisSource;
		},
		
		addTweetLinks: function(tweetText){
			//make links
			var thisTweet = tweetText;
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			var thisTweet = thisTweet.replace(exp,"<a href=\"$1\">$1</a>"); 
			var exp = /[\@]+([A-Za-z0-9-_]+)/ig;
			thisTweet = thisTweet.replace(exp,"<a href=\"http://twitter.com/$1\">@$1</a>"); 
			return thisTweet;
		},
		
		isBadTweet: function(tweetText){
			var badTweet = false;
			if(badWordsList){
                badWords = badWordsList.split(",");
                $.each(badWords, function(w,badWord){
                	if(tweetText.toLowerCase().indexOf(badWord) > -1)
                		badTweet = true;
                });
			}
			return badTweet;
		},
		
		writeNoTweets: function(){
			var noTweetsHTML = "";
			if(commentsType == "page") {
				var noTweetsHTML = "<td><div class=\"notweets-btn\"><button id=\"signin_launch\" title=\"Sign in with Twitter\"></button></div><div class=\"create_account\">New to Twitter? <a href=\"http://www.twitter.com/signup\">Create an account</a></div></td>";	      
				$('<tr></tr>')
					.html(noTweetsHTML)
					.appendTo('#'+parentdiv+' #'+twitterTableID);
				$('#'+parentdiv+' #signin_launch')
					.click(function() {
						$.cwtwitter.openOverlay();
					});
			}
			else if(commentsType == "overlay") {
				noTweetsHTML = "<div><strong>Please Sign In and Post</strong>Be the first. See your tweet here and on your Twitter account page.</div>";
				$('#'+parentdiv+' #content .left').hide();
				$('#'+parentdiv+' #first-tweet')
					.html(noTweetsHTML)
					.show();
			}

		},
		
		writeFailWhale: function(){
			$('#'+parentdiv+' h3.update').text("Twitter updates are not working");
			$('#'+parentdiv+' #'+twitterTableID).html("<tr><td><div class=\"twitter_down\"><p>Please check back in a few moments to view and post tweets.</p></div></td></tr>");
		},
		
		openOverlay: function(){
		    var doch = $(document).height();
		    var docw = $(document).width();
		    var winh = $(window).height();
		    var winw = $(window).width();
		    var xoffset = $(document).scrollLeft();
		    var yoffset = $(document).scrollTop();
		    var overlayh = 593;
		    var overlayw = 726;
		    var bottomadsh = 125;    
		    if(loadAds == 1) overlayh = overlayh + bottomadsh;
		   
			$('body')
				.prepend('<div class="twitter_overlay_inner" id=""></div><div class="twitter_overlay" id=""></div>');
			$('.twitter_overlay')
				.css({width:docw, height:doch, display:"block"})
				.fadeIn("fast");
			$('.twitter_overlay_inner')
				.css({top:((winh-overlayh)/2)+yoffset, left:((winw-overlayw)/2)+xoffset})
				.html('<div id="twitter_app"></div>');
			$('#twitter_app')
				.html('<span class="close" id="twitter_overlay_close">Close</span><div id="twitter_app_header"></div><div id="content"></div><div id="twitter-bottom-ads" style="display:none;"></div><div id="first-tweet" style="display:none;"></div>');
			$('#twitter_app_header')
				.html('<h3 class="update"></h3><h4 class="tag"><span class="keyword">'+twKeyword+'</span></h4><span class="poweredby cso">Powered by Twitter</span>');
			$('#twitter_app #content')
				.html('<div class="left" style=""></div><div class="right"></div>');
			$('#twitter_app #content .left')
				.html('<div class="refresh"></div><div id="twitter_content"></div>');
			$('#twitter_app #twitter_content')
				.html('<table id="tweetlist" cellpadding="0"></table><div id="btn_search_twitter"><a class="more" href="http://twitter.com/#search?q='+twKeyword+'">More '+twKeyword+' results from Twitter</a></div>');
			$('#twitter_app #content .right')
				.html('<div class="content"></div>');
			$('#twitter_app #content .right .content')
				.html('<div id="twitter-top-ad"></div><div class="signed_in clearfix" style="display:none;">You are signed in <span style="color:#999">|</span> <a id="signout">Sign out</a></div><div class="tweet_form clearfix"></div><div class="ad-180x150"></div>');
			$('#twitter_app #twitter-top-ad')
				.html('<div id="ad_88x31"></div>');
			$('#twitter_app .tweet_form')
				.html('<form id="tw-form"><fieldset><legend>Sign in and post to Twitter</legend><div class="error" style="display: none;"></div><h3 id="what_thinking">What are you thinking?</h3><div class="bar"> <a id="insert-url">Insert this article url</a> <span class="numeric" id="chars_left_notice"> <strong class="char-counter" id="status-field-char-counter" style="color:#666666;"></strong></span></div><textarea tabindex="1" autocomplete="off" accesskey="u" name="status" class="" id="status" rows="4" cols="28">#'+twKeyword+'</textarea><div class="signin_fields" style="display:none;"></div><div class="status-btn"><button type="submit" tabindex="4" id="update-submit" value="update" name="update">Update</button><a class="cancel" style="display:none;">Cancel</a><div class="create_account">New to Twitter? <a href="http://www.twitter.com/signup">Create an account</a></div><span class="tweetsent" style="display:none;">Tweet sent</span></div></fieldset></form>');
		    $('#status-field-char-counter')
		    	.text(140-($('#status').val().length));
			$('.signin_fields')
				.html('<label for="username">Username or email</label><input tabindex="2" title="username" value="" name="" class="text" id="username" type="text"><label for="password">Password</label><input tabindex="3" title="password" value="" class="text" name="" id="password" type="password"><span class="message">CSO Online does not store your password</span>');
			
			// load tweets
			$.cwtwitter.getTweets({numTweets:8,commentsType:"overlay"});
			
			if(loadAds == 1){
				if (!self.ord) { ord = Math.random()*10000000000000000; }
				$('#twitter_app #ad_88x31')
					.html('<iframe width="88" height="31" src="/spring/module.htm?moduleType=ad&position=twitter_logo&taxonomyId='+taxonomyid+'&moduleLayout=ad-layout" scrolling="no" frameborder="0"></iframe>');
				$('#twitter_app .ad-180x150')
					.html('<iframe width="180" height="150" src="/spring/module.htm?moduleType=ad&position=twitter_square_banner&taxonomyId='+taxonomyid+'&moduleLayout=ad-layout" scrolling="no" frameborder="0"></iframe>');
				$('#twitter_app #twitter-bottom-ads')
					.html('<iframe width="350" height="100" src="/spring/module.htm?moduleType=ad&position=twitter_leadgen1&taxonomyId='+taxonomyid+'&moduleLayout=ad-layout" scrolling="no" allowtransparency="true" frameborder="0"></iframe><iframe width="350" height="100" src="/spring/module.htm?moduleType=ad&position=twitter_leadgen1&taxonomyId='+taxonomyid+'&moduleLayout=ad-layout" scrolling="no" allowtransparency="true" frameborder="0"></iframe>')
					.show();
			}
			// if cookie exists, show that user is logged in
			var cookieName = "_twitter_auth_token"
			if(document.cookie.indexOf(cookieName) > -1){
				$('.create_account').hide();
				$('.signed_in').show();
			}
			// else show login boxes
			else {
				$('.signin_fields').show();
			}
			$('#status')
				.keyup(function(){
					$.cwtwitter.countChars();
				});
			$('#insert-url')
				.click(function() {
					var thisURL = window.location;
					$.getJSON("http://api.bit.ly/shorten?version=2.0.1&longUrl="+thisURL+"&format=json&login=cwdev&apiKey=R_26b0303ad062dd9a46abc500a5ba6bc7&callback=?",function (b) {
						var blah="";
						$.each(b.results, function(i,item){
					        var enteredStatus = $('#status').val();
					        $('#status').val(item.shortUrl+" "+enteredStatus);
					        $.cwtwitter.countChars();
				          });
						return false;
					});
				});
			$('#signout')
				.click(function(){
					//delete cookie
					var currDate = new Date();
				    document.cookie = cookieName+"=;expires=" + currDate.toGMTString() + ";path=/";
					//hide "logged in" div
				    $('.tweetsent').hide();
				    $('.create_account').show();
					$('.signed_in').hide();
					$('.signin_fields').show();
				});
			$('a.cancel')
				.click(function(){
					$('#what_thinking').text("What are you thinking?");
					$('#status').val('#'+twKeyword);
					$.cwtwitter.countChars();
					$(this).hide();
				});
			$('#update-submit')
				.click(function(){
					setClickTrackingVars('twitter_expanded_updatetweet - onclick',this);
				});
			$('#twitter_app #tw-form')
				.submit(function() {
					if($('#status').val().length <= 140){
					$.post('/twitterproxy/status/',{username:$('.tweet_form #username').val(), password:$('.tweet_form #password').val(), status:$('.tweet_form #status').val()},function(data){
						// no error code, successful post
						if($(data).find('created_at').text()) {
							// empty old tweets
							$('#twitter_app #tweetlist').empty();
							// write user's tweet
							/*var thisUserName = $(data).find('status').find('user').find('screen_name').text();
							var thisUserImgURL = $(data).find('status').find('user').find('profile_image_url').text();
							var newTweetText = $(data).find('status').find('text').text();
							var newTweetFText = $.cwtwitter.addTweetLinks(newTweetText);
							
							var userImgHTML = "<td><div class=\"profile-pic\"><a href=\"http://www.twitter.com/"+thisUserName+"\"><img src=\""+thisUserImgURL+"\" width=48 height=48 alt=\""+thisUserName+"\" class=\"photo\" /></a></div></td>";                          
							var userNameHTML = "<span class=\"username\"><a title=\"\" class=\"screen-name\" href=\"http://www.twitter.com/"+thisUserName+"\">"+thisUserName+"</a></span>";
							var sourceHTML = "<span class=\"source-meta\">just now from web</span>";
							var statusHTML = "<span class=\"status-body\">"+newTweetFText+"</span>";
							var newTweetHTML= userImgHTML+"<td><div class=\"dialog\"><div class=\"content\"><div class=\"pointer\"></div><div class=\"t\"></div><span class=\"entry-meta\">"+userNameHTML+sourceHTML+"</span>"+statusHTML+"</div><div class=\"b\"><div></div></div></div></td>";
							$('<tr></tr>')
								.html(newTweetHTML)
								.appendTo('#twitter_app #tweetlist');
								
							// get only seven new tweets to go with faked user tweet
							$.cwtwitter.getTweets({numTweets:7, commentsType:"overlay"});*/
							
							// get new tweets
							$.cwtwitter.getTweets({numTweets:8, commentsType:"overlay"});
							
							$('#tw-form .error').hide();
							$('#tw-form #what_thinking').text("What are you thinking?").show();
							$('#status').removeClass('error').val('#'+twKeyword).show();
							$.cwtwitter.countChars();
							$('a.cancel').hide();
							$('.tweetsent').show();
							$('.create_account').hide();
							$('.signed_in').show();
							$('.signin_fields').hide();
						}
						// 401: auth failed
						else if($(data).find('errorcode').text() == '401') {
							$('#tw-form #what_thinking').hide();
							$('#tw-form .error').html("Wrong Username/Email and password combination. Try again. <a href=\"http://twitter.com/account/resend_password\">Having trouble?</a>").show();
						}
						// some other response
						else {
							$('#tw-form #what_thinking').hide();
							$('#tw-form .error').html("An error has occurred. Please try again later.").show();
							//alert("Unexpected error.  Sorry. :(");
						}
					});
					}
					return false;
				});
			
			$('#twitter_overlay_close').bind("click", function(e){
				setClickTrackingVars('twitter_expanded_close - onclick',this);
		 		$(".twitter_overlay_inner").fadeOut("fast");
		 		$(".twitter_overlay").fadeOut("fast");
		 		$(".twitter_overlay_inner").empty().remove();
		 		$(".twitter_overlay").remove();
			});
			
			$('#twitter_app .refresh')
				.html("<a>Refresh results</a>")
				.click(function(){
					$("#twitter_app #tweetlist").empty();
					$.cwtwitter.getTweets({numTweets:8,commentsType:"overlay"});
				});
			
			$('.twitter_overlay_inner').fadeIn("fast");
		},
		
		countChars: function(){
			var fieldlen = $('#twitter_app #status').val().length;
		    var charsRemain = 140-fieldlen;
		    $('#twitter_app #status-field-char-counter').text(charsRemain);
		    if (fieldlen > 140) {
		        // error - too many chars entered
		        $('#twitter_app #status').addClass("error");
		        $('#twitter_app #status-field-char-counter').css("color","#990000");
		        $('#twitter_app .tweet_form button#update-submit').addClass('disabled');
		    } 
		    else {
		    	$('#twitter_app #status').removeClass("error");
		    	$('#twitter_app #status-field-char-counter').css("color","#666666");
		    	$('#twitter_app .tweet_form button#update-submit').removeClass('disabled');
		    } 
		}
	};	
})(jQuery);