var IS = window.IS || [];

IS.Twitter = {
	init : function() { // determine page and load appropriate twitter feed js
		var body, b, url = false, page, display, height;
			body = jQuery('body:first');
			//b = jQuery(body).attr('id');
            
            page = '';
            display = 3;
            height = 64;
            
            if (jQuery('#col1').hasClass('qa-testing-page')) { //use the non-cached QA Twitter feed for testing purposes
                url = 'http://news.instyle.com/feedmaster/?feed_name=qa&format=jsonp&callback=IS.Twitter.create';
            } else {
                url = 'http://www.instyle.com/instyle/static/json/twitter/global.js';
            }
            
		IS.Twitter.page = page;
		IS.Twitter.display = display;
		IS.Twitter.height = height;
		IS.Twitter.tweetspeed = 8000;
		IS.Twitter.sponsorspeed = 12000;
		IS.Twitter.show = false;
		if (url) {jQuery.getScript(url);};
	},
	formatlinks : function(str) { // humbly borrowed from http://tutorialzine.com/2009/10/jquery-twitter-ticker/...  AWESOME!
		str = ' '+str;
		str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
		str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
		str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
		return str;
	},
	create : function(obj) { // called by feed js
		if (!obj || obj.tweets.length == 0) return false; // make sure we got a file back
		var celeb, sw, show, screen_name, name, profile_image_url, headline, h = '';
		celeb = (this.page == 'celebpage') ? true : false; // determine if a celeb db page
		sw = (this.page == 'stylewatch') ? true : false; // determine if a stylewatch page
		show = 'block'; // used to hide/show LIs initially
		screen_name = obj.tweets[0].screen_name;
		name = obj.tweets[0].name;
		profile_image_url = obj.tweets[0].profile_image_url;
		headline = (obj.headline == null) ? '' : obj.headline;
		if (celeb) {
			//obj.tweets.reverse(); // re-order tweets bottom-to-top
			h += '<h2><a target="_blank" href="http://twitter.com/'+screen_name+'"><strong>'+IS.Twitter.celebname+':</strong> Tweet Ticker</a></h2>';
			h += '<span class="author">'; // pic & screen_name
				h += '<a class="profile-pic" target="_blank" href="http://twitter.com/'+screen_name+'"><img alt="'+name+'" src="'+profile_image_url+'" height="48" width="48"></a>';
				h += '<span class="nickname"><a class="url" target="_blank" href="http://twitter.com/'+screen_name+'" title="'+name+'">@'+screen_name+'</a></span> ';
			h += '</span> ';
		} else {
			h += '<h3>Tweet Ticker</h3>';
		};
		h += '<div class="celeb">';
		if (!celeb) {h += '<p class="title">'+headline+'</p>';};
		h += this.buildtweets(obj.tweets);
		if (!celeb) {
			if (sw) {
				h += '<p class="more"><a target="_blank" href="http://twitter.com/stylewatchmag">Follow @StyleWatchMag</a></p>';
			} else {
				h += '<p class="more"><a target="_blank" href="http://twitter.com/instyle">Follow @InStyle</a> on Twitter</p>';
			};
		};
		h += '</div>';
		if (this.page != 'celebpage' && obj.ads != null) {
			h += this.buildsponsor(obj.ads);
		};
		if (this.show) { // if we got at least one tweet...
			jQuery('#twitterfeed').html(h).slideDown('slow').addClass('active');
			if (obj.tweets.length > this.display) { // if there are more tweets than the display count initiaite cycling
				if (celeb) { // determine correct cycle function
					jQuery('#twitterfeed').addClass('toutSection inside');
					//setInterval('IS.Twitter.cyclecelebs()',this.tweetspeed);
				} else {
					setInterval('IS.Twitter.cycletweets()',this.tweetspeed);
					if (jQuery('#sponsortweets').find('li').length > 1) {setInterval('IS.Twitter.cyclesponsors()',this.sponsorspeed);};
				};
			};
			this.tracking();
		};
	},
	buildtweets : function(o) { // build OL of tweets
		if (!o || o.length == 0) return false;
		var celeb, c, h, text, screen_name, name, profile_image_url, created_at, source, tweets = 0;
		celeb = (this.page == 'celebpage') ? true : false; // determine if a celeb db page, don't cycle if so
		c = (o.length <= this.display) ? o.length : this.display;
		h = '<div class="tweets" style="height:'+(c * this.height)+'px;">';
			h += '<ol id="celebtweets" class="hfeed">';
			for (i = 0; i < o.length; i++) {
				if (o[i].text != '') { // make sure tweet has content
					text = this.formatlinks(o[i].text); // format all the links, grab all tweet content
					screen_name = o[i].screen_name;
					name = o[i].name;
					profile_image_url = o[i].profile_image_url;
					source = o[i].source;
					h += '<li id= "tweet-'+i+'" class="hentry">';
						if (!celeb) {h += '<a class="profile-pic" target="_blank" href="http://twitter.com/'+screen_name+'"><img alt="'+name+'" src="'+profile_image_url+'" height="48" width="48"></a>';};
						h += '<span class="entry-content">';
							if (!celeb) {h += '<span class="author"><span class="fn">'+name+'</span> (<a class="url" target="_blank" href="http://twitter.com/'+screen_name+'">'+screen_name+'</a>):</span> ';};
							h += '<span class="entry-title">'+text+'</span>';
							if (celeb) { // celeb timestamp
								timestamp = this.buildtimestamp(o[i].created_at);
								h += '<span class="meta entry-meta">';
									h += '<span class="entry-date published timestamp" data="{time:\''+created_at+'\'}">'+timestamp+'</span> ';
									h += '<span>from '+source+'</span>';
								h += '</span>';
							};
						h += '</span>';
					h += '</li>';
					tweets++; // make sure we get at least one tweet or don't write into page
				};
			};
			h += '</ol>';
			if (celeb) {
				h += '<p class="more"><a target="_blank" href="http://twitter.com/'+screen_name+'">More Tweets</a></p>';
			};
		h += '</div>';
		if (tweets > 0) {
			this.show = true;
			return h;
		};
	},
	buildsponsor : function(o) { // build OL of sponsors
		if (!o || o.length == 0) return false;
		var c, h, text, screen_name, name, profile_image_url, ads = 0;
		c = (o.length <= this.display) ? o.length : this.display;
		h = '<div class="sponsor">';
			h += '<p class="title">From Our Sponsors</p>';
			h += '<div class="tweets">';
				h += '<ol id="sponsortweets" class="hfeed">';
				o.sort(this.randomize); // randomize order of sponsor tweets
				for (i = 0; i < o.length; i++) {
					if (o[i].text != '') {
						text = this.formatlinks(o[i].text);
						screen_name = o[i].screen_name;
						name = o[i].name;
                        profile_image_url = o[i].profile_image_url;
						h += '<li id= "tweet-'+i+'" class="hentry">';
                            h += '<a class="profile-pic" target="_blank" href="http://twitter.com/'+screen_name+'"><img alt="'+name+'" src="'+profile_image_url+'" height="48" width="48"></a>';
							h += '<span class="entry-content">';
								h += '<span class="author"><span class="fn">'+name+'</span> (<a class="url" target="_blank" href="http://twitter.com/'+screen_name+'">'+screen_name+'</a>):</span> ';
								h += '<span class="entry-title">'+text+'</span>';
							h += '</span>';
						h += '</li>';
						ads++;
					};
				};
				h += '</ol>';
			h += '</div>';
		h += '</div>';
		if (ads > 0) {
			return h;
		};
	},
	buildtimestamp : function(o) {
		// from	'Wed Aug 13 00:52:59 +0000 2008' to '9:38 PM MAY 27th'
		var d, t, hour, minutes, ampm, m, mon, day, s;
			d = o.split(' ');
			t = d[3].split(':');
			hour = (String(t[0]) == '00') ? '12' : this.removezero(t[0]);
			if (Number(hour) > 12) {hour = Number(hour) - 12;};
			minutes = String(t[1]);
			ampm = (Number(hour) > 12) ? 'PM' : 'AM';
			mon = String(d[1]).toUpperCase();
			day = Number(d[2]);
			s = 'th';
			if (day == 1 || day == 21 || day == 31) {s = 'st';};
			if (day == 2 || day == 22) {s = 'nd';};
			if (day == 3 || day == 23) {s = 'rd';};
		return hour+':'+minutes+' '+ampm+' '+mon+' '+day+s;
	},
	cycletweets : function() { // moves last tweet to top
		jQuery('#celebtweets').find('li:last').css('display','none').prependTo(jQuery('#celebtweets')).animate({'height':'toggle','opacity':'toggle'},700);
	},
	cyclesponsors : function() { // moves last tweet to top
		jQuery('#sponsortweets').find('li:last').css('display','none').prependTo(jQuery('#sponsortweets')).animate({'height':'toggle','opacity':'toggle'},700);
	},
	cyclecelebs : function() { // moves first tweet to bottom
		var li = jQuery('#celebtweets li:first');
			li.slideUp('slow',function(){
				li.css('display','none').appendTo(jQuery('#celebtweets')).slideDown('slow');
			});
	},
	tracking : function() { // adds omniExit(domain,description) onclick to links in tweets
		var b = adFactory.params.ch, desc = 'Twitter ';
		if (b == 'homepage') { // determine appropriate description: Twitter Article; Twitter Homepage; Twitter Celeb; Twitter Article Sponsor; Twitter Homepage Sponsor; Twitter Celeb Sponsor, etc.
			desc += 'Homepage';
		} else if (b == 'news') {
			desc += 'Article';
		} else if (b == 'celebrity') {
			desc += 'Celeb';
		} else if (b == 'style watch') {
			desc += 'StyleWatch';
		} else if (b == 'tvwatch') {
			desc += 'TVWatch';
		} else {
			desc += 'Sponsor';
		};
		this.tracking.description = desc;
		jQuery('#twitterfeed a').each(function(){ // grab all links in tweets and sponsors and bind omniExit() to each, with appropriate domain, description
			jQuery(this).click(function(){
				var d = this.href.split('/');
				var domain = d[2].replace(/www\./,'');
				omniExit(domain,IS.Twitter.tracking.description);
			});
		});
	},
	removezero : function(v) { // utility to remove 0 from 01-09
		if (Number(v) < 10) {v = String(v).replace(/0/,'');} return v;
	},
	randomize : function() { // randomize order
		return (Math.round(Math.random())-0.5);
	}
};
jQuery(function($){
    IS.Twitter.init();
});
