// JavaScript objects used to manage the Tweet tabs and update them at regular intervals
// Coded by Marian Busoi 4 Copimaj

Tweetective = function() { };
Tweetective.prototype = {
				query : function (tabid) {
							// searches the Twitter site for a particular keyword
							var escaped, url, listQuery = false;
							var mode = (arguments.length>1 && arguments[1] == 'update') ? 'update' : 'load';
							
							if(tm.tabs[tabid].q.substr(0, 5) == 'list:') {
							  // query user list
							  listQuery = true;
							  escaped = escape(tm.tabs[tabid].q.substr(5));
							  url = 'includes/ajax/list_get.php?callback=?&list=' + escaped;
							} else {
								escaped = escape(tm.tabs[tabid].q);
								escaped = escaped.replace(/%u2019/g, "'");
								url = tm.twitterBaseURL + 'search.json?callback=?&rpp=50&q=' + escaped;
								if (mode == 'update'){
									var url = tm.twitterBaseURL + 'search.json' + tm.tabs[tabid].refresh_url + '&rpp=50&callback=?';
								}								
							}
							
							$.getJSON(url, null,
								  function(data) {	
								  	if(!tm.tabs[tabid]) return false;
									  else {
										receiver = '#' + tm.tabs[tabid].container;
										
										if ($(receiver) && data) {
										  var results = listQuery ? data : data.results;
										  
										  if(results) {
											  var count = results.length; // # of search results
											  
											  switch(mode){
												  case 'load':
													  $(receiver).find("li").remove();
														
													  for(var i = 0; i < count - 1; i++) {
															newResult = $(tm.tabs[tabid].scout.parseResult(results[i], tm.tabs[tabid].q));
														  $(receiver).append(newResult);
														  newResult.hide().animate({height: 'toggle'}, 1000, 'swing');
													  }
														newResult =$(tm.tabs[tabid].scout.parseResult(results[count-1], tm.tabs[tabid].q));
														$(receiver).append(newResult);
														newResult.hide().animate({height: 'toggle'}, 1000, 'swing');
												  break;
												  case 'update':
														if(count) {
															for(var i = count-1; i > 0; i--) {
																newResult = $(tm.tabs[tabid].scout.parseResult(results[i], tm.tabs[tabid].q));
																$(receiver).prepend(newResult);
																newResult.hide().animate({height: 'toggle'}, 1000, 'swing');
															}
															newResult = $(tm.tabs[tabid].scout.parseResult(results[0], tm.tabs[tabid].q));
															$(receiver).prepend(newResult);
															newResult.hide().animate({height: 'toggle'}, 1000, 'swing');
														}
												  break;
											  }
											  
											  tm.tabs[tabid].refresh_url = data.refresh_url;
										  } else if(data.error) {
											  $('#basic-modal-content').html("Twitter says: " + data.error);
											  $('#basic-modal-content').modal( { autoResize: false, maxWidth: 300, maxHeight: 150, position: ['30%'] } );
										  }
										  
										  setTimeout('if(tm.tabs[' + tabid + ']) tm.tabs[' + tabid + '].scout.query(' + tabid + ', "update")', 10000);
										  
										} else {
										  	$('#basic-modal-content').html("Oops. We made a boo-boo: " + data);
											$('#basic-modal-content').modal( { autoResize: false, maxWidth: 300, maxHeight: 150, position: ['30%'] } );
										}
									}
							});
						},
						
						linkify : function (text, qu) {
								if(!text) return text;
								
								
								if(qu.substr(0, 5) == 'from:') qu = qu.substr(11);
								
								var isInLink = false;
								
								text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
										function(url){
											if(url.indexOf(qu)!=-1) isInLink = true;
											nice = url;
											if( url.match('^https?:\/\/') )
											{
												nice = nice.replace(/^https?:\/\//i,'')
											}
											else
												url = 'http://'+url;
											
											
											return '<a target="_blank" rel="nofollow" href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>';
										});
								
								if(!isInLink)	// boldify keyword if we don't have links containing it
									text = text.replace(new RegExp("[^@#]" + qu, "gi"),	// boldify
											function(keyword){
												return '<strong>'+ keyword +'</strong>';
											});											
								
								return text;
						},
						
						twittify : function (text) {
								if(!text) return text;
								
								text = text.replace(/@([a-zA-Z0-9_]+)/gi,	// @ links
										function(tweeter){
											nice = tweeter.substr(1);
											
											return '<a target="_blank" rel="nofollow" href="http://twitter.com/'+ nice +'">'+ tweeter +'</a>';
										});
								
								text = text.replace(/#([a-zA-Z0-9_]+)/gi,	// # links
										function(tweeter){
											return '<a target="_blank" rel="nofollow" href="http://twitter.com/search?q='+ escape(tweeter) +'">'+ tweeter +'</a>';
										});					
								
								return text;
						},							

						parseResult : function (data, qu) {
							var searchResult = '';
							
							if(data) {
								var d = new Date(data.created_at);
								var day = d.getDate();
								day = (day < 10 ? "0" : "") + day;
								var month = d.getMonth() + 1;
								month = (month < 10 ? "0" : "") + month;
								var h = d.getHours();
								h = (h < 10 ? "0" : "") + h;
								var m = d.getMinutes();
								m = (m < 10 ? "0" : "") + m;
								
								var from_user = data.from_user ? data.from_user : data.user.screen_name;
								var profile_image_url = data.profile_image_url ? data.profile_image_url : data.user.profile_image_url;
								
								searchResult = '<li class="clearfix">';
								searchResult += '<div class="img_options">';
								searchResult += '<a class="reply" target="_blank" href="http://twitter.com/home?status=' + escape('@' + from_user) + '&source=ftwitt&in_reply_to_status_id=' + data.id + '" title="Reply">reply</a>';
								searchResult += '<a class="view_profile" href="http://twitter.com/' + from_user + '" target="_blank" title="View profile">View profile</a>';
								var escaped = escape('RT @' + from_user + ' ' + data.text);
								escaped = escaped.replace(/%u2019/g, "'"); // fix url encode bug
								searchResult += '<a class="retweet" target="_blank" href="http://twitter.com/home?status=' + escaped + '" title="Retweet">Retweet</a>';
								searchResult += '</div>';								
								searchResult += '<div class="tw_image" onmouseover="$(this).find(\'.img_options\').css(\'display\', \'block\');" onmouseout="$(this).find(\'.img_options\').css(\'display\', \'none\');">';
								searchResult += '<a href="http://twitter.com/' + from_user + '" class="thumb_img" target="_blank">';
								searchResult += '<img border="0" src="' + profile_image_url + '" alt="' + from_user + '" />';
								searchResult += '</a>';
								searchResult += '</div>';
								searchResult += '<div class="user_details">';
								searchResult += '<h4>';
								searchResult += '<a href="http://twitter.com/' + from_user + '" target="_blank">';
								searchResult += from_user;
								searchResult += '</a>';
								searchResult += '</h4>';
								searchResult += ' <span class="time">' + h + ':' + m +' <span>' + day + '/' + month + '</span></span>';
								searchResult += '</div>';
								searchResult += '<p>' + this.twittify( this.linkify(data.text, qu) ) + '</p>'; 
								searchResult += '</li>';
							}
							
							return searchResult;
						}
				};
				
Tweetmanager = function() { };				

Tweetmanager.prototype = {
						tabs : [], // no tabs first
						savedTabs: [], // tabs we're saving to cookie
						tabCount : 0, 
						contentWidth : 0,
						trends: [],
						isLoggedIn: false,
						workGroup: 0,
						twitterBaseURL : 'http://search.twitter.com/',
						sortOrigin: 0,
						
						markTab: function (i, save) {
							this.savedTabs[i] = true;
							if(!save) this.saveCookie();
						},
						
						unmarkTab: function (i) {
							this.savedTabs[i] = false;
							this.saveCookie();
						},						
						
						saveTab: function (i, caller) {
							this.markTab(i);
							$(caller).html( 'Search saved' );
						},

						addTabs : function (qu) {
							var queryType = arguments.length>1 && arguments[1] == 'accounts' ? 'accounts' : (arguments[1] == 'list' ? 'list' : 'search');
							
							if (typeof(qu) == 'object') {
							  for(q in qu)
							  	if(qu[q]) {
									if(queryType == 'search') this.addTabs(qu[q]);
									else this.addTabs(qu[q], arguments[1]);
								}
							} else {
								qu = unescape(qu);
								var len = this.tabs.length;
								
								var booboo = false;
								
								for(var i=0; i< tm.tabs.length; i++){
									if(	tm.tabs[i] && tm.tabs[i].q == qu ) {
										theQuery = qu;
										if(queryType == 'accounts') theQuery = theQuery.substr(5);
										$('#basic-modal-content').html("This tab is already opened: <strong>" + theQuery + "</strong>");
										$('#basic-modal-content').modal( { autoResize: false, maxWidth: 300, maxHeight: 150, position: ['30%'] } );
										booboo = true;
										break;
									} 
								}
								
								if(!booboo)	{				
								
									var id = 'tweettab' + len;
									var parentID = 'tweetparent' + len;
									var titlebar = '';
									
									if(queryType == 'search') 
										titlebar = '<span>Search for:</span> ' + qu;
									else if(queryType == 'list')
										titlebar = '<span>List:</span> ' + qu.substr(qu.indexOf(':')+1);
									else
										titlebar = '#' + qu.substr(11);

									$('#column_container').prepend('<li class="tabWrapper" id="' + parentID + '"' + (this.isLoggedIn ? '' : ' onmouseover="$(this).find(\'.saveButton\').show();" onmouseout="$(this).find(\'.saveButton\').hide();"') + '><div class="tabHeader">' + (this.isLoggedIn ? '' : '<div class="saveButton"><a href="javascript:void(0)" onclick="tm.saveTab(' + this.tabs.length + ', this)">Save your search</a></div>') + '<span class="title">' + titlebar + '</span> <a class="close" title="close" href="#" onclick="tm.removeTab(' + this.tabs.length + ')">close</a></div><ul class="tabListing" id="' + id + '"><li class="clearfix"><img src="images/loading.gif" class="loadingGif" /></li></ul></li>');
	
									this.tabs.push({q: qu, container: id, parent: parentID, refresh_url: null, scout: new Tweetective(), type: queryType});
									this.tabCount++;
									this.tabs[this.tabs.length - 1].scout.query(this.tabs.length - 1);
									
									if(queryType == 'accounts')
										$('.' + qu.substr(11)).addClass('active'); // make the button active
										
									smartColumns();
									
									if (this.isLoggedIn) {
										if(this.workGroup > 0) {
											$.getJSON('includes/ajax/groups_new_tab.php?callback=?', {id: this.workGroup, q: escape(qu)},
													function (data) {
														if(data && data.error) {
															$('#basic-modal-content').html( data.error );
															$('#basic-modal-content').modal( { autoResize: false, maxWidth: 300, maxHeight: 150, position: ['30%'] } );
														}
														else { 
															$('#group_' + this.workGroup).animate({opacity: 0}, 1000, 'swing', function () { $(this).animate({opacity: 1}, 1000, 'swing'); });
														}
													});
										}
									}
								}
							}
						},
						
						removeTab : function(tabid) {
							if(this.tabs[tabid]) {
								$('#' + this.tabs[tabid].parent).remove();
								this.tabCount--;
								if(this.tabs[tabid].type == 'accounts')
									$('.' + this.tabs[tabid].q.substr(11)).removeClass('active');
								
								this.savedTabs[tabid] = false;
								
								if (this.isLoggedIn) {
									if(this.workGroup > 0) {
										$.getJSON('includes/ajax/groups_delete_tab.php?callback=?', {id: this.workGroup, q: escape(this.tabs[tabid].q)},
												function (data) {
													if(data && data.error) {
														$('#basic-modal-content').html( data.error );
														$('#basic-modal-content').modal( { autoResize: false, maxWidth: 300, maxHeight: 150, position: ['30%'] } );
													}
													else { 
														
													}
												});
									}
								}	

								this.tabs[tabid] = null;
								
								smartColumns();
							}
						},
						
						wipeOut : function() { // removes all tabs and cleans up
							$('#column_container').empty();
							
							this.tabs = [];
							this.tabCount = 0;
							this.savedTabs = [];
						},
						
						bullets : function(count) {
							var str = "";
							
							for(i = 0; i<count; i++)
								str += "<img src='images/dot.png' alt='tab' />&nbsp;";
							
							return str;
						},

						fetchTrends: function(target) {
							var url = this.twitterBaseURL + 'trends/current.json?callback=?';
							var caller = this;
							
							$.getJSON(url, null,
									  function (data) {
										for(x in data.trends)
									 		if(typeof(data.trends[x]) == 'object')
												for(y in data.trends[x]) {
													caller.trends.push(data.trends[x][y]);
													
													if($(target))
														$(target).append("<li><a href='#' title='" + data.trends[x][y].name + "' onclick='tm.addTabs(\"" + escape(data.trends[x][y].query) + "\")'>" + data.trends[x][y].name + '</a></li>');
												}
												
												
										$('#trends').hover(function () { clearTimeout(trendsHide); });
										$('a.trends_head').click(function () {
											$(this).addClass('btn_main_active');
											$('#trends').show();
											$('#trends').parent().hover(
												function (){ }, 
												function (){ 
													clearTimeout(trendsHide);
													trendsHide = setTimeout("$('ul#trends').hide(); $('a.trends_head').removeClass('btn_main_active');", 500);
												}
											);
											
										});
										
									  });
						},
						
						saveCookie : function() {
							var cs = '';
							
							for (x in tm.savedTabs) {
								if (tm.savedTabs[x]) {
									if(cs != '') cs += '|**|';
									cs += tm.tabs[x].q + "|//|" + tm.tabs[x].type;	
								}
							}

							$.cookie('ftwitttabs', cs, {expires: 60}); // expire in 2 months	

							if(arguments.length && tm.isLoggedIn){
								var tabObj = arguments[1].item;
								var index = $(arguments[0].target).find("li.tabWrapper").index(tabObj[0]);
								
								var tabIndex = tabObj.attr('id').substr(11);
								
								var q = tm.tabs[tabIndex].q;
								var gid = tm.workGroup;
								
								var dir = tm.sortOrigin < index ? "r" : "l"; // moved to left/right ?
								
								$.getJSON('includes/ajax/groups_tab_order.php?callback=?', {gid: tm.workGroup, query: escape(q), order: index, direction: dir},
										function (data) {
											if(data && data.error) {
												$('#basic-modal-content').html( data.error );
												$('#basic-modal-content').modal( { autoResize: false, maxWidth: 300, maxHeight: 150, position: ['30%'] } );
											}
										});								
							}
						}
				   };
				   
var tm = new Tweetmanager();
$(document).ready ( function () { 
						var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
						
						if(IE6) {
							alert("Sorry, but old browsers, like Internet Explorer 6, are not supported by FTwitt. Please consider upgrading your browser!");
							$(document).empty();
						} else {
							if( $('.btn_create_gr').size() ) tm.isLoggedIn = true;
							
							tm.fetchTrends('#trends'); 
							
							$('.account').bind(
								'click',
								function()
								{
									var qu = 'from:ftwitt' + $(this).find("span").html().toLowerCase();
									tm.addTabs( escape(qu), 'accounts' );
									return false;
								}
							);
							// Load tabs from cookie
							var tabs = $.cookie('ftwitttabs');
							$.cookie('ftwitttabs', null); // remove cookie
							if(tabs){ // if the user has some tabs saved, let's add them
								tabs = tabs.split("|**|");
								for(var i=tabs.length - 1; i>=0; i--){
									tmp = tabs[i].split("|//|");
									if(tmp && tmp.length==2){
										tm.markTab(tm.tabs.length, true);
										tm.addTabs(escape(tmp[0]), tmp[1]);	
									}
								}
							}	

							bindGroupLinks();
							/*$('.l_link').bind(
								'click',
								function()
								{
									$(this).parent().toggleClass("active");
									return false;
								}
							);			*/					
						}
					} 
				  );