jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/* ----- Read all about it: http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area/841121#841121 ----- */
$.fn.selectRange = function( start, end ) {
	return this.each( function() {
		if ( this.setSelectionRange ) {
			this.focus();
			this.setSelectionRange( start, end );
		} else if ( this.createTextRange ) {
			var range = this.createTextRange();
			range.collapse( true );
			range.moveEnd( "character", end );
			range.moveStart( "character", start );
			range.select();
		}
	});
};


/* ----- TweetMixx JS ----- */
var tm = {};

tm.channels = {
	chatter: function() {
		var container = $( "div#tweets" ), loaders = $( "div.loading", container ), retry_anchors = $( "a.retry", loaders );
		
		if ( container.length ) {
			loaders.each( function() {
				tm.util.loadLinkData( $( this ), 1 );
			});
			
			tm.util.checkForNewTweets( "/ping/chatter" );
			tm.util.paginate( container );
		}
	},
	
	insiders: function() {
		var container = $( "div#tweets" ), loaders = $( "div.loading", container ), retry_anchors = $( "a.retry", loaders );
		
		if ( container.length ) {
			loaders.each( function() {
				tm.util.loadLinkData( $( this ), 1 );
			});
			
			tm.util.checkForNewTweets( "/ping/insiders" );
			tm.util.paginate( container );
		}
	},
	
	pagelets: {
		carousel: function() {
			$( "div.pagelet.carousel" ).each( function() {
				var animating = false, prev = $( "a.previous", $( this ) ), next = $( "a.next", $( this ) ), ul = $( "ul", $( this ) ), li_width = $( "li:first", $( this ) ).outerWidth();
				
				ul.css( "width", ( li_width * $( "li", ul ).length ) );
				
				var ul_width = ul.width(), first_margin = 0, last_margin = ul_width - li_width;
				
				var animateCarousel = function( point ) {
					animating = true;
					
					ul.animate( { marginLeft: point + "px" }, "slow", "swing", function() {
						animating = false;
					});
				}
				
				prev.click( function() {
					if ( !animating ) {
						var curr_margin = parseFloat( ul.css( "margin-left" ) ), new_margin = curr_margin + li_width;

						if ( new_margin > 0 ) animateCarousel( "-" + last_margin );
						else animateCarousel( new_margin );
					}
					
					return false;
				});
				
				next.click( function() {
					if ( !animating ) {
						var curr_margin = parseFloat( ul.css( "margin-left" ) ), new_margin = curr_margin - li_width;

						if ( Math.abs( new_margin ) >= ul_width ) animateCarousel( 0 );
						else animateCarousel( new_margin );
					}
					
					return false;
				});
			});
		},
		
		retweeter: function( retweeter_htmlclass ) {
			var data = channel_retweeters[retweeter_htmlclass];
			
			if ( null == data ) return;

			var duplicate_message = "Sorry, but you've already posted this tweet!"
			var pagelet = $( "div.pagelet.retweeter." + retweeter_htmlclass ), pagelet_heading = $( "div.hd h3", pagelet ), pagelet_body = $( "div.bd p", pagelet ), pagelet_anchor = $( "div.ft a", pagelet ), pagelet_confirmation = $( "p.confirmation", pagelet );
							
			var cookie_name = tm_channel_name + '_' + retweeter_htmlclass, retweeter_cookie = $.cookie( cookie_name ), sent_prop_id = Number( retweeter_cookie ), was_sent = null != retweeter_cookie && !isNaN( sent_prop_id );
			var tweets = data.tweets, prev_tweets = [];
			
			// remove the previous tweets
			if ( window.localStorage && localStorage.getItem('prev_tweet_indices') ){
				var prev_tweet_indices = localStorage.getItem('prev_tweet_indices');
				if (null != prev_tweet_indices)
					prev_tweets = JSON.parse(prev_tweet_indices);	
			}	
			
			if (was_sent) {
				prev_tweets[prev_tweets.length] = Math.abs( sent_prop_id )
				if( window.localStorage )
					localStorage.setItem('prev_tweet_indices', JSON.stringify(prev_tweets));
			}

			for (var i = null == tweets ? -1 : tweets.length - 1;  i >= 0; i--) {
				var temp_tweet = tweets[i]
				if( -1 < jQuery.inArray( temp_tweet.id, prev_tweets ) )
					tweets.splice( i, 1)
			}
		
			var tweet_index = null;		
			var tweet = null;
			if (null != tweets && tweets.length > 0) {//
			    tweet_index = Math.round(Math.random() * (tweets.length - 1));
				tweet = tweets[ tweet_index ];
			}

            if ( was_sent ) {
				pagelet_confirmation.html( sent_prop_id >= 0 ? data.completion : duplicate_message );				
			} else if ( null != retweeter_cookie && retweeter_cookie.indexOf("duplicate" ) > -1 )
				pagelet_confirmation.html( duplicate_message );
			
			// remove the cookie
			$.cookie( cookie_name, null, { expires:-1 } );
			
			if (null == tweet) {
				pagelet_heading.html("We are all out of tweets");
				pagelet_body.html("Thanks for your help tweeting!");
				pagelet_anchor.parent().html("");			
			}
			else {
				pagelet_heading.html(data.instruction);
				pagelet_body.html(tweet.text);
				pagelet_anchor.attr("href", tweet.url);
			}
		}
	}
};

var allow_refresh = true;

tm.util = {
	checkForNewTweets: function( url ) {
		var delay_in_seconds = 60, div = $( "div#updates-available" );
		
		var t = setTimeout( function() {
			if(allow_refresh) {
				$.ajax({
					type: "get",
					cache: false,
					url: $( "a#update_link" )[0].href,
					dataType: "json",
					success: function( rsp ) {
						if ( rsp.updates > 0 ) {
							clearTimeout( t );
							window.location.reload();
						} else {
							tm.util.checkForNewTweets( url );
						}
					}
				});
			} else {
				tm.util.checkForNewTweets( url );
			}
		}, delay_in_seconds * 1000 );
	},
	
	flashes: function() {
		var delay_in_seconds = 10, div = $( "div.flash", "div#primary-content" );
		
		if ( div.length ) {
			setTimeout( function() {
				div.fadeOut( "slow", function() {
					div.remove();
				});
			}, delay_in_seconds * 1000 );
		}
	},
	
	initMediaOverlay: function() {
		var body = $( "body" ), container = $( "div#content" ), anchors = $( "a.show-media", container );
		
		anchors.live( "click", function() {
			var anchor = $( this ), hentry = anchor.parents( ".hentry" ), media = $( "div.media", hentry ).clone(), curtain = $( '<div id="media-curtain"></div>' ), viewer = $( '<div id="media-viewer"><img src="/images/tweetmixx/close.png" alt="Close" id="closer" /></div>' );
			allow_refresh = false;
			
			curtain.css({
				filter: "alpha(opacity=50)",
				height: $( document ).height()
			}).appendTo( body ).fadeIn( "slow" ).click( function() {
				allow_refresh = true;
				tm.util.removeOverlay( [viewer, curtain] );
			});
			
			viewer.prepend( media ).appendTo( body ).css({
				left: ( $( window ).width() - viewer.width() ) / 2,
				top: anchor.offset().top - 100
			}).fadeIn( "slow" );
			
			$( "img#closer" ).click( function() {
				allow_refresh = true;
				tm.util.removeOverlay( [viewer, curtain] );
				return false;
			});
			
			return false;
		});
	},
	
	initGetWidgetOverlay: function() {
		var body = $( "body" ), anchor = $( "a#get-widget-anchor, img#get-widget-image" );
		
		anchor.click( function() {
			var curtain = $( '<div id="widget-curtain"></div>' ), viewer = $( '<div id="widget-viewer"><img src="/images/tweetmixx/close.png" alt="Close" id="closer" /></div>' ), code_container = $( "div#get-widget-code" ).clone(), textarea = $( "textarea", code_container );
			
			curtain.css({
				filter: "alpha(opacity=50)",
				height: $( document ).height()
			}).appendTo( body ).fadeIn( "slow" ).click( function() {
				tm.util.removeOverlay( [viewer, curtain] );
			});
			
			viewer.prepend( code_container ).appendTo( body ).css({
				left: ( $( window ).width() - viewer.width() ) / 2,
				top: anchor.offset().top
			}).fadeIn( "slow" );
			
			textarea.selectRange( 0, textarea.val().length );
			
			$( "img#closer" ).click( function() {
				tm.util.removeOverlay( [viewer, curtain] );
				return false;
			});
			
			return false;
		});
	},
	
	loadLinkData: function( loader, i ) {
		var max_attempts = 6, delay_in_seconds = 3, linked_url = loader.attr( "title" ), loader_original_html = loader.html(), loader_failure_html = '<p>Oh, no! We couldn\'t load that link. <a href="" class="retry">Try again?</a></p>', loader_no_retry_html = '<p>Oh, no! We couldn\'t load that link.</p>', loader_error_html = '<p>Oh, no! This link is currently unavailable.</p>';
		
		if ( i < max_attempts ) {
			setTimeout( function() {
				$.ajax({
					type: "get",
					cache: false,
					url: "/ajax/link?url=" + linked_url + "&channel=" + tm_channel_id + "&tab_id=" + tm_tab_id,
					dataType: "json",
					success: function( rsp ) {
						if ( rsp.status == "success" ) {
							var markup = $( rsp.markup );

							loader.fadeOut( "slow", function() {
								loader.replaceWith( markup );
								markup.prev( "div.tweet" ).addClass( "linked" );
								markup.show();
							});
						} else {
							tm.util.loadLinkData( loader, ++i );
						}
					}
				});
			}, delay_in_seconds * 1000 );
		} else {
			loader.remove();
		}
	},
	
	paginate: function( container ) {
		$( "div.pagination a" ).click( function() {
			var anchor = $( this ), anchor_original_html = anchor.html(), anchor_loading_html = $( '<img src="/images/tweetmixx/loading.gif" alt="" />' );
			
			$.ajax({
				type: "get",
				cache: false,
				url: anchor.attr( "href" ),
				dataType: "json",
				beforeSend: function() {
					anchor.html( anchor_loading_html );
				},
				success: function( rsp ) {
					if ( rsp.status == "success" ) {
						var markup = $( rsp.markup );
						
						container.append( markup );
						
						$( "div.loading", markup ).each( function() {
							tm.util.loadLinkData( $( this ), 1 );
						});
						
						if ( !rsp.is_more ) {
							anchor.fadeOut( "fast", function() {
								anchor.remove();
							});
						} else {
							if ( rsp.next_max_id )
								anchor.attr( "href", anchor.attr( "href" ).replace( /max_id=[0-9]*/, "max_id=" + rsp.next_max_id ) );
							else if ( rsp.next_page )
								anchor.attr( "href", anchor.attr( "href" ).replace( /page=[0-9]*/, "page=" + rsp.next_page ) );
							
							anchor.html( anchor_original_html );
						}
					} else {
						anchor.fadeOut( "fast", function() {
							anchor.remove();
						});
					}
				}
			});
			
			return false;
		});
	},
	
	removeOverlay: function( elems ) {
		$( elems ).each( function() {
			var elem = $( this );
			
			elem.fadeOut( "slow", function() {
				elem.remove();
			});
		});
	},
	
	updateStatus: function() {
		var form = $( "form#update-status-form" );
		
		if ( form.length ) {
			var textarea = $( "textarea#update_tweet" ), maxlength = textarea.attr( "maxlength" ), counter = $( "li#update-counter" );
			
			textarea.keyup( function() {
				var count = maxlength - textarea.val().length;

				counter.html( count );
				if ( count < 0 ) counter.addClass( "overboard" );
				else counter.removeClass( "overboard" );
			});

			var count = maxlength - textarea.val().length;

			counter.html( count );
			if ( count < 0 ) counter.addClass( "overboard" );
			counter.fadeIn( "fast" );
		}
	}
};

$().ready( function() {
	if ( $( "body#page_channel_chatter" ).length ) tm.channels.chatter();
	if ( $( "body#page_channel_insiders" ).length ) tm.channels.insiders();
	
	tm.channels.pagelets.carousel();
	
	tm.util.flashes();
	tm.util.initGetWidgetOverlay();
	tm.util.initMediaOverlay();
	tm.util.updateStatus();
});