/**
 * jQuery nbcTwitter
 * 
 * Copyright (c) 2009 NBC Universal (http://www.nbc.com)
 * @author Justin Anderson
 * Use restricted without expressed written permission.
 *
 * 
 * @example $('#twitter').nbcTwitter();
 * @name nbcTwitter
 * @type jQuery
 * @param Hash o A set of key/value pairs to set as configuration properties.
 *
 * todo: add loader
 */
var nbcTwitter;
(function($){
	$.fn.nbcTwitter = function(o){
		return this.each(function(){
			new $tw(this,o);
		});
	};
	var defaults = {
		src:					'/assets/esp/twitter/feed/',
		siteId:				null,
        // categoryId:         null,
		limit:				3,
		page:				1,
		maxPages:			10,
		debug:				false,
		baseURI:			'www.nbc.com',
		method:				'getStatus1',
		condition:		[],
		username:			null,
		orderBy:			'status_publish_date',
		order:				'DESC',
		moreTweets:		true,
		moreLabel:		'More Tweets',
		moreURL:			null,
		toSCET:				true,
        targetSection:      null,
        targetSelector:     null
	}
	
	nbcu.util.common.loadClass("Nbcu.Template");
	
	$.nbcTwitter = function(e,o){
		this.options  = $.extend({},defaults, o || {});		
		this.container = e;		
		//this.totalRecords = null;		
		this.siteId = this.options.siteId || (typeof showId !='undefined'?showId:null);
        // this.categoryId = this.options.categoryId || (typeof categoryId != 'undefined' ? categoryId : null);
		
		this.init();
	}
	
	$tw = $.nbcTwitter;	
	
	$tw.fn = $tw.prototype = {
		nbcTwitter: '0.1'
	};
	
	$tw.fn.extend = $.extend;

	
	$tw.fn.extend({
		init: function(){
			this.debug('Init nbcTwitter'); //debug
			this.json();
		},
		json: function(){
			
			this.debug('json nbcTwitter'); //debug

			var conditional = '';
			//var defaultCond = (this.options.username != null?'user_username='+this.options.username:'')+'category_is_active=1,user_is_active=1,status_is_acitve=1';
			var defaultCond = (this.siteId!=null?'site_id='+this.siteId+',':'')+(this.options.username!=null?'user_username='+this.options.username+',':'')+'cxu_is_active=1,category_is_active=1,user_is_active=1,status_is_active=1';
			if(this.options.condition != '')
				conditional = this.options.condition.join()+','+defaultCond;
			else
				conditional = defaultCond;
			var order = this.options.order.toUpperCase();
			var url = this.options.src+this.options.method+'/where/'+conditional+'/page/'+this.options.page+'/perPage/'+this.options.limit+'/order/'+this.options.orderBy+'='+order+'/index.json';
            // debug info:
            // alert('url: ' + url);

			this.debug(url);
			var self = this;			
		
			$.ajax({
				type: 			'GET',
				url:				url,
				dataType:		'json',
				beforeSend: function(xhr){xhr.setRequestHeader("X-Framework-JSON-Request", "PLAINJSON");},
				success: 		function(data){self.tweets(data);},
				error: 			function(XMLHttpRequest, textStatus, errorThrown){
					self.debug('XMLHttpRequest='+XMLHttpRequest+'\ntextStatus='+textStatus+'\nerrorThrown='+errorThrown);
				},
				complete:   function(){self.debug('ajax GET complete')}
			});
		},	
		goToPage: function(page){
			this.options.page = page;
			this.json();
			location.href = "#tweets";
		},
		tweets: function(data){
			var self 		= this;
			var uri 		= this.showURI();
			this.debug(this.container); //debug
			var output 	= '<div id="twitter-wrap"><a name="tweets"></a>';
			var statuses = data.pageRecords;			
			this.debug(statuses); //debug
			$.each(statuses,function(i,tweet){
				self.debug(i);
				self.debug('toScet'+self.options.toSCET);
                    
                    if (typeof self.options.targetSection != 'undefined') {
                        if (self.options.targetSection == 'emmys-nominees') {
                            if (typeof self.options.targetSelector != 'undefined' && self.options.targetSelector == 'twitter') {
                                uri = 'http://twitter.com';
                            }
                        }
                    }
					var s = tweet;
					output+='<div class="tweet-wrap '+(i%2?'even':'odd')+'">\n';
			        output+='<a class="tweet-avatar" href="http://twitter.com/'+s.user_username+'" target="_blank"><img src="'+s.user_avatar_uri+'" alt="'+s.user_username+'" /></a>\n';
			        output+='<a class="tweet-title" href="http://twitter.com/'+s.user_username+'" target="_blank">'+s.user_username+'</a>\n';
					//output+='<a class="tweet-avatar" href="'+uri+'/twitter/#tweetIDnum'+s.status_id+'"><img src="'+s.user_avatar_uri+'" alt="'+s.status_username+'" /></a>\n';
					//output+='<a class="tweet-title" href="'+uri+'/twitter/#tweetIDnum'+s.status_id+'">'+s.status_username+'</a>\n';
					/*if(self.options.toSCET == true){
                        if (typeof self.options.targetSection != 'undefined') {
                            if (self.options.targetSection == 'emmys-nominees' && typeof self.options.targetSelector != 'undefined' && self.options.targetSelector == 'twitter') {
						        output+='<a class="tweet-avatar" href="'+uri+'/'+s.user_username+'" target="_blank"><img src="'+s.user_avatar_uri+'" alt="'+s.user_username+'" /></a>\n';
						        output+='<a class="tweet-title" href="'+uri+'/'+s.user_username+'" target="_blank">'+s.user_username+'</a>\n';
                            } else {
						        output+='<a class="tweet-avatar" href="'+uri+'/twitter/"><img src="'+s.user_avatar_uri+'" alt="'+s.user_username+'" /></a>\n';
						        output+='<a class="tweet-title" href="'+uri+'/twitter/">'+s.user_username+'</a>\n';
                            }
                        } else {
						    output+='<a class="tweet-avatar" href="'+uri+'/twitter/"><img src="'+s.user_avatar_uri+'" alt="'+s.user_username+'" /></a>\n';
						    output+='<a class="tweet-title" href="'+uri+'/twitter/">'+s.user_username+'</a>\n';
                        }
					}else{
						output+='<img src="'+s.user_avatar_uri+'" alt="'+s.user_username+'" />\n';
						output+='<p class="tweet-title">'+s.user_username+'</p>\n';
					}*/
					String.prototype.parseURL = function() {
						return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/gi, function(url) {
							return '<a href="'+url+'" target="_blank">'+url+'</a>';
						});
					};
		 
					String.prototype.parseUsername = function() {
						return this.replace(/[@]+[A-Za-z0-9-_]+/gi, function(u) {
							var username = u.replace("@","")
							return '@<a href="http://twitter.com/'+username+'" target="_blank">'+username+'</a>';
						});
					};
					
					String.prototype.parseHashtag = function() {
						text = this.replace(/(^|)#(\w+)/gi, function (s) {
        					return '<a href="http://search.twitter.com/search?q=' + s.replace(/#/,'%23') + '" target="_blank">' + s + '</a>';
						});
						return text;
					};
					output+='<p class="tweet-text">'+s.status_text.parseURL().parseUsername().parseHashtag()+'</p>\n';
					output+='<p class="tweet-published">'+nbcu.template.helper.friendlyDate(s.status_publish_date, "Pacific")+'</p>\n';
					output+='</div>\n';
			});
			if(this.options.moreTweets){
				var moreURL = this.options.moreURL||uri;
				output+='<a class="more-tweets" href="'+moreURL+'/twitter/">'+this.options.moreLabel+'</a>';
			}
			
			nbcTwitter = this;
			if(this.options.paginate) {
				output+=nbcu.template.helper.getPager(this.options.page, this.options.maxPages, this.options.limit, data.totalRecords, "javascript:void(0);", "nbcTwitter.goToPage(%page%);");
			}
			output+='</div>';
			this.debug('json complete'); //debug		
			$(this.container).html(output);
		},
		loader: function(){
			
		},
		showURI: function(){
			var url 			= window.location.href;
			var nohttp 		= url.replace('http://','');
			var urlArray 	= nohttp.split('/');
			var showURI 	= '';
	
			if(urlArray[0] == this.options.baseURI || urlArray[0] == 'dev.nbc.nbcuni.com')
				showURI = '/'+urlArray[1];
			
			return showURI;
		},
		error: function(msg){
			this.debug(msg);
		},
		debug: function(s){
			if(this.options.debug == true){
				if(window.console && window.console.log && !$.browser.msie)
					console.log(s);
				else
					alert(s);
			}
		}
	});

})(jQuery);

