/**
 *
 * Twitter
 *
 */
var Twitter;
 
var twitterApi = function(cont)
{
	Twitter = this;
	var name = "twitter";
	var self = this;
	var container = $('#engagementData');
	var feedsize  = 'large';
	var events = false;
	var reqObj;
	var target = '#engagementData';
	var $user;
	
	var $temp = {};
	$(document).ready(function() {
		$temp.feeditem = $.ajax({
			url:'/js/apis/twitter/templates/feeditem.html',
			global: false,
			async: false
		}).responseText;
	});
	
	this.setUser = function(user){
		$user = user;
	}
	
	this.setContainer = function(cont)
	{
		container = $(cont);
	}
	
	this.getTemp = function(temp) {
		return
	}
	
	this.share = function(item)
	{
		var data = {};
		data.message = '';
		return data;
	}
	
	this.parse = function(data)
	{
		if($defined(data.rows))
		{
			var tmp = [];
			$.each(data.rows, function(){
				var doc = this.doc;
				doc.item_type = doc.type;
				doc.type = 'facebook';
				doc.ago = new Date().ago(doc.updated_time);
				tmp.push(doc);
			})
		}
		return data;
	}
	this.feed = function(cb){
		$.ajax({
			global: false,
			type:'GET',
			url: '/apis/twitter/feed/json',
			dataType:"json",
			data:{},
			beforeSend: function(xhr) {
				xhr.setRequestHeader("AuthSession", $.cookie('AuthSession'))
			},
			success: cb,
			error: function(){
				alert('There was an error with your search');
			}
		});
	}
	// Initializes a feed item
	this.initItem = function(data)
	{
		var item = $.tmpl($temp.feeditem,data);
		var fi = $(item);
		return self.initEvents(fi);
	}
	
	this.initEvents = function(fi)
	{
		var screenName = fi.find('input[name=screen_name]').val();
	      
		if($defined(screenName))
		{
			fi.find('.user-icon').bubbletip('click',{
				direction:'right',
				action:'ajax',
				content:'/apis/twitter/getUser/'+screenName+'/element',
				'style':'bubbletip userData'
			}).css('cursor','pointer');
		}
	      
		// Set the reply links
		fi.find('.reply').click(function(){
			var user = self.user();
			$(this).pTemp('twitter/templates/reply.html',user,'Twitter.replyBox');
			return false;
		});
	      
		// set the retweet links
		fi.find('.retweet').click(function(){
			var data = {};
			data.id = $(this).attr('rel');
			var i = $(this).parent().find('.share').attr('rel');
			data.message = $('#'+i).find('.message').html();
			$(this).pTemp('twitter/templates/retweet.html',data,'Twitter.retweetBox');
			return false;
		});
	      
		// set the retweet links
		fi.find('.follow').click(function(){
			var data = {};
			var i = $(this).parents('.feedItem');
			data.photo = $(i).find('.userPhoto').attr('src');
			data.screen_name = $(this).attr('rel');
			$(this).pTemp('twitter/templates/follow.html',data,'Twitter.followBox');
			return false;
		});
	      
		$(fi).find('img').each(function(){
			var s = $(this).attr('src');
			if(s.substr(0,5) == 'http:')
			{
				$(this).attr('src','/images.php?i='+encode64(s));
			}
		});	      
		return fi;
	}
	
	// Creates the options
	this.options = function(){
		var o = [];
		o.push({
			'name':'All',
			'method':'loadAll'
		});
		o.push({
			'name':'@Replies',
			'method':'loadReplies'
		});
		o.push({
			'name':'Following',
			'method':'loadFollowing'
		});
		o.push({
			'name':'Keywords',
			'method':'loadKeywords'
		});
		return o;
	}
	
	this.loadKeywords = function()
	{
		user = $.cookie('user');
		if(typeof user != 'object')
		{
			user = jQuery.parseJSON(user);
		}
	      
		var key = new TwitterKeywords();
		key.init(user.guid);
	}
	
	// Loads the users mentions
	this.loadMentions = function()
	{
		this.getFeed('mentions');
		return this;
	};
	
	// Loads the following feed
	this.loadFollowing = function()
	{
		this.getFeed('following');
		return this;
	};
	
	this.loadReplies = function()
	{
		this.getFeed('replies');
		return this;
	};
	
	this.loadAll = function()
	{
		this.getFeed('all');
		return this;
	};
	
	this.displayFeed = function(data, status, obj)
	{
		$(target).empty();
		if(!data.length > 0)
		{
			$(target).html('<h1>No Available Data</h1>');
			return false;
		}
		$(data).each(function(){
			var i = self.initItem(this);
			$(target).append(i);
		});
	}
	
	this.getFeed = function(type,options)
	{
		$(target).setLoading();
		// Removed options area if displayed
		if($defined('#optionsArea') && $('#optionsArea').html() != '')
		{
			$('#optionsArea').empty();
		}
		var opts = jQuery.extend({
			dataType: 'json',
			global: false,
			type:'POST',
			success: function(data,status,obj){
				self.displayFeed(data,status,obj);
				$(self).trigger('feedloaded');
			},
			error : function() {
				alert('There was an error');
			},
			url: '/apis/twitter/get/'+type+'/json'
		}, options);
		$.ajax(opts);
	};
	
	
	
	this.user = function()
	{
		if(typeof $user == 'object')
		{
			return $user;
		}
		$user = this.request('getUser','json');
		return $user;
	};
	
	this.request = function(url,format,rdata)
	{
		this.reqObj = $.ajax({
			dataType: 'json',
			async: false,
			global: false,
			type:'POST',
			data: rdata,
			url: '/apis/twitter/'+url
		});
		return (format=='json') ? JSON.parse(this.reqObj.responseText):this.reqObj.responseText;
	};
	
	this.requestFeed = function(url,target,d)
	{
		var rdata = {
			'feedsize':feedsize
		};
		if(d!='')
		{
			rdata = $.extend(rdata,d);
		}
		$(target).setLoading();
	      
		var r = $.ajax({
			async: true,
			global: false,
			url: '/apis/twitter/'+url,
			data: rdata,
			success: function(data){
				$(target).trigger('contentLoaded');
				$(target).empty().append(data);
			//$(target).append($('<a href="">Load More</a>'));
			},
			error: function(){
				$(target).empty().html('There was an error with your search');
			}
		});
		return r;
	};
	
	this.staticSent = function(resp, form)
	{
		$('#chars-left').html(140);
		$('#engageBox').find('#postText').val('');
		var e = $.create('div',{
			'id':'notice',
			'class':'info'
		});
		$(e).html('<p>Your Status Has Been Updated</p>').css({
			'display':'none'
		});
		$(form).offsetParent().append($(e));
		$(e).fadeIn('fast',function(){
			setTimeout(function(){
				$(e).fadeOut()
			},3000);
		})
	};
	
	this.sent = function(resp, form)
	{
		$(form).html('Your message has been sent');
		setTimeout('closeBox()',2000);
	};
	
	this.followed = function (resp, form)
	{
		$('h1#title').html('Success!');
		$(form).html('You are now following their tweets.');
		setTimeout('closeBox()',2000);
	}
	
	this.followBox = function(box,link)
	{
		var form = $(box).find('form');
		$(form).attr('action','/apis/twitter/post/follow').withAjax({
			'callback':'Twitter.followed'
		});
	};
	
	this.retweetBox = function(box,link)
	{
		var form = $(box).find('form');
		var msg = $(link).parents('.feedItem').find('.message').html();
		$(box).find('.message').html(msg);
		$(form).attr('action','/apis/twitter/post/retweet').withAjax({
			'callback':'Twitter.sent'
		});
	};
	
	this.successBox = function(box)
	{
		var form = box.find('form');
		$(form).html('Your tweet has been sent.');
	}
	this.replyBox = function(box, link)
	{
		var form = $(box).find('form');
		form.find('textarea').val('@'+$(link).attr('rel')).addCounter();
		$(form).attr('action','/apis/twitter/post/reply').withAjax({
			'callback':'Twitter.sent'
		});
	};
	
	// Add a twitter counter to a form object
	$.fn.addCounter = function(){
	  $('<div class="charsLeft">Characters Left: <span id="charsCount">140</span></div>').appendTo($(this).parent());
	  $(this).bind({
		'keydown':function(event){
			var max = 140;
			var cur = $(this).val().length;
			var tot = max - cur;
			$(this).parent().find('#charsCount').html(tot);
			if(tot <= 0 && (event.keyCode != 8 && event.keyCode != 46))
			{
				return false;
			}		  
			return true;
		}
	  });
	  $(this).trigger('keydown');
	  return this;
	}
	}
	
	var Keywords;
	function TwitterKeywords(options) {
	Keywords = this;
	var self = this;
	var $guid;
	this.currentWord = '';
	
	var opts = jQuery.extend({
		container: $('#engagementData'),
		kType: 'member'
	}, options);
	
	var kType = opts.kType;
	
	// Verify twitter core is loaded
	Twitter = new twitterApi();
	
	var container = opts.container;
	
	if(typeof container != 'object')
	{
		container = $(container);
	}
	
	var $temp = {};
	
	this.init = function(guid)
	{
		$temp.keywords = self.getTemplate('twitter/templates/keywords.html');
	      
		data = {};
		data.guid = guid;
		data.type = 'member';
		$guid = guid;
		container.empty().html($.ele('h2',{
			'style':'text-align:center;padding:10px;'
		}).html('Enter your search above'));
		var keywordsBox = $.tmpl($temp.keywords,data);
		$('#optionsArea').empty().append(keywordsBox).slideDown();
		this.keywordEvents();
		this.loadWords();
	}
	
	this.getTemplate = function(temp) {
		return $.ajax({
			url:'/js/apis/' + temp,
			global: false,
			async: false
		}).responseText;
	}
	
	this.keywordEvents = function()
	{
		$('#keywordManager').find('.addKeyword form').withAjax({
			'callback':'Keywords.keywordSent',
			'error':'Keywords.keywordError'
		});
	      
		$('#keywordText').unbind().click(function(){
			$('#keywordText').val('');
		});
	      
		// /apis/twitter/add_keyword
		$('#keywordManager').find('.addKeyword form').unbind('submit').submit(function(){
			return false;
		});
	      
		$('#keywordManager').find('#search').unbind().click(function(){
			var p = {};
			p.keyword = $('#keywordText').val();
			p.save    = $('#saveFor:checked').val();
			if(p.keyword=='')
			{
				alert('You must first enter a keyword');
				return false;
			}
			self.keywordSearch(p);
		});
	      
		// Create the keyword dropdown
		var exp = $.create('img',{
			'id':'dispSaved',
			'src':'/images/icons-ui/note.png'
		});
	      
		// Unbind any previous events
		$('#keywords-tracked').unbind().css({
			'zIndex':'100'
		});
		$(exp).unbind().mouseenter(self.showKeywords).click(self.hideKeywords);
		$('#keywords-tracked').mouseleave(self.hideKeywords);
		$('#keywordText').parent().append($(exp));
	      
		// Add the map events
		$('#keywordMap').unbind().click(function(){
			self.hideKeywords();
			if($('.keywordLocation').css('display') == 'none')
			{
				$('.keywordLocation').slideDown();
				$('.keywordLocation').find('#location').addClass('inactive').val('City, State');
				$('.keywordLocation').find('#location').click(function(){
					$(this).removeClass('inactive').val('');
				});
			}
			else
			{
				$('.keywordLocation').slideUp();
			}
		});
	      
		$('#keywords-tracked li').each(function(){
			var data  = {
				'id':$(this).attr('id'),
				'keyword':$(this).find('span').html()
			};
			$(this).unbind().click(function(){
				self.hideKeywords();
				self.keywordSearch(data);
				$('#keywordText').val(data.keyword);
				return false;
			});
		    
			$(this).find('.keywordDelete').unbind().click(function(event){
			event.preventDefault();
			if(confirm('Are you sure you want to delete this?'))
			{
				self.hideKeywords();
				self.rmKeyword(data.id);
			}
			});
		});
	}
	
	this.loadWords = function()
	{
		self.hideKeywords();
		// zindex fix for ie
		$('#keywordManager').css({
			'zIndex':200
		});
		// Get the keywords Type
		var keywords = this.request('getKeywords/'+$guid,'json');
		if(keywords.length > 0)
		{
			$('#keywords').empty();
			$.each(keywords,function(){
				var word = this.keyword;
				var id   = this.id;
				var del  = $.create('img',{
					'class':'keywordDelete',
					'src':'/images/icons/chiclet-close.png'
				});
			  
				var li = $.create('li',{
					id:id,
					'class':'kw'
				});
			  
				var l  = $(li).html('<span>'+word+'</span>');
				if(kType!='member' || (kType == 'member' && this.scope=='member'))
				{
					$(l).append($(del));
				}
			  
				$('#keywords').append($(l));
			});
		    
			this.keywordEvents();
		} else {
		  $('#keywords').empty().html('<div class="noWords">You are not tracking any words, use the box above to add some.</div>');
		}
		return keywords.length > 0 ? keywords:false;
	}
	
	this.keywordSent = function(resp, form)
	{
		self.hideKeywords();
		$(form).find('#keywordText').val('');
		this.loadWords();
		this.keywordSearch(resp.args);
	}
	
	this.keywordSelected = function()
	{
		if(typeof self.currentWord == 'object') return self.currentWord;
		if(!$chk($('#keywords-tracked li.selected')))
		{
			return false;
		}
		var data  = {
			'id':$('#keywords-tracked li.selected').attr('id'),
			'keyword':$('#keywords-tracked li.selected').find('span').html()
		};
		return data;
	}
	
	this.request = function(url,format,rdata)
	{
		this.reqObj = $.ajax({
			dataType: 'json',
			async: false,
			global: false,
			type:'POST',
			data: rdata,
			url: '/apis/twitter/'+url
		});
		return (format=='json') ? JSON.parse(this.reqObj.responseText):this.reqObj.responseText;
	};
	
	/*
	 * Run the keyword search
	 */
	this.keywordSearch = function(w)
	{
		self.keywordStatusReset();
		container.setLoading();
		var d = self.keywordLocation();
		if(w != '')
		{
			var msg = urldecode(w.keyword);
			if(w.save=='on')
			{
				msg += ' [Saved]';
				this.saveKeyword();
			}
			if(typeof d == 'object')
			{
				msg += ' within '+d.within+' miles of '+d.location;
			}
			var k = self.request('searchKeyword/'+urlencode(w.keyword)+'/json','json',d);
			container.empty();
			$(k).each(function(key){
				var item = Twitter.initItem(this);
				container.append(item);
			});
			setTimeout(function(){
				self.keywordStatus('Results For: ' + msg,'done');
			},200);
		}
	};
	
	this.keywordStatusReset = function(){
		$('#keywordStatus').html('').removeClass().fadeOut();
	}
	
	this.keywordStatus = function(msg,cl)
	{
		$('#keywordStatus').removeClass()
		.addClass(cl)
		.html(msg)
		.slideDown();
	}
	
	
	this.showKeywords = function()
	{
		var words = $('#keywords-tracked').find('li').length;
		if(words > 0)
		{
			$('#keywords-tracked').css('z-index',20).slideDown('fast');
		}
	}
	
	this.hideKeywords = function()
	{
		$('#keywords-tracked').slideUp('fast');
	}
	/**
	 * Display the keyword error box
	 */
	this.keywordError = function(r, form){
		var e = $.create('div',{
			'id':'notice',
			'class':'error'
		});
		$(e).html('<p>'+r.text+'</p>').css({
			'display':'none'
		});
		$(form).offsetParent().append($(e));
		$(e).fadeIn('fast',function(){
			setTimeout(function(){
				$(e).fadeOut()
			},3000);
		})
	}
	
	this.keywordLocation = function(){
		if($('.keywordLocation').css('display') != 'none')
		{
			if($('.keywordLocation').find('#location').val() != '')
			{
				data = {};
				data.location = $('.keywordLocation').find('#location').val();
				data.within   = $('.keywordLocation').find('#within').val();
				return data;
			}
		}
		return false;
	}
	
	
	/**
	 * Delete a keyword
	 */	
	this.rmKeyword = function(w)
	{
		$('#keywords').setLoading('small');
		this.request('remove_keyword/'+w+'/'+$guid);
		this.loadWords();
		this.keywordStatus('Keyword Deleted','done');
	};
	
	this.saveKeyword = function(data)
	{
		$.ajax({
			url: '/apis/twitter/add_keyword',
			data: $('#keywordManager').find('.addKeyword form').serialize(),
			type: 'POST',
			dataType: 'json',
			success: function() {
				$('#saveFor').attr('checked', false);
				self.loadWords();
			}
		});
	};
}

