function TwitterDisplay(operation, criteria, resultsPerPage, containerId, callback, tagLabel) {
	this.operation = jQuery.trim(operation);
	this.criteria = jQuery.trim(criteria);
	this.resultsPerPage = resultsPerPage;
	this.containerId = containerId;
	this.callback = callback;
	this.currentPage = 0;
	this.totalPages = 500;
	if(tagLabel) {
		this.tagLabel = tagLabel;
	} else {
		this.tagLabel = "Tag(s) : ";
	} 
	if(operation == 'statuses') {
		this.requestURL = "http://twitter.com/statuses/user_timeline/" + this.criteria + ".json";
		this.nextPageUrlSuffix = "?page=1&count=" + this.resultsPerPage;
		this.refreshUrlSuffix = "?page=1&count=" + this.resultsPerPage
		
	} else {
		this.requestURL = "http://search.twitter.com/search.json";
		this.nextPageUrlSuffix = "?page=1&rpp=" + this.resultsPerPage + "&q=" + this.criteria;
		this.refreshUrlSuffix = "?page=1&rpp=" + this.resultsPerPage + "&q=" + this.criteria;

	}
	this.prevPageUrlSuffix = "";
}

/*
TwitterDisplay.prototype.displayNextPage = function() {
	if(this.currentPage < this.totalPages) {
		this.currentPage = parseInt(this.currentPage) + 1 ;
		var requestURL = this.requestURL + this.nextPageUrlSuffix + "&rand=" + parseInt(Math.random()*99999999) + "&callback=?" ;
		$.getJSON(requestURL, this.callback);
	}
	
}*/
TwitterDisplay.prototype.displayNextPage = function(){
	if (this.nextPageUrlSuffix != "") {
		this.currentPage = parseInt(this.currentPage) + 1;
		var requestURL = this.requestURL + this.nextPageUrlSuffix + "&rand=" + parseInt(Math.random() * 99999999) + "&callback=?";
		$.getJSON(requestURL, this.callback);
		$("#" + this.containerId).html("<div class='ajaxLoading'>Loading ...</div>");
	}
}	
/*
TwitterDisplay.prototype.displayPrevPage = function() {
	if(this.currentPage > 1) {
		this.currentPage = parseInt(this.currentPage) - 1;
		var requestURL = this.requestURL + this.prevPageUrlSuffix + "&rand=" + parseInt(Math.random()*99999999) + "&callback=?" ;
		$.getJSON(requestURL, this.callback);
	}	
}*/

TwitterDisplay.prototype.displayPrevPage = function() {
if(this.prevPageUrlSuffix != "") {
	this.currentPage = parseInt(this.currentPage) - 1;
		var requestURL = this.requestURL + this.prevPageUrlSuffix + "&rand=" + parseInt(Math.random()*99999999) + "&callback=?" ;
		$.getJSON(requestURL, this.callback);
		$("#" + this.containerId).html("<div class='ajaxLoading'>Loading ...</div>");
	}	
}


TwitterDisplay.prototype.refreshPage = function(){
	if (this.refreshUrlSuffix != "") {
		this.currentPage = parseInt(this.currentPage) + 1;
		var requestURL = this.requestURL + this.refreshUrlSuffix + "&rand=" + parseInt(Math.random() * 99999999) + "&callback=?";
		$.getJSON(requestURL, this.callback);
		
		$("#" + this.containerId).html("<div class='ajaxLoading'>Loading ...</div>");
		var container = $("#" + this.containerId + " .tweetsHolder");
		container.fadeOut(2000, function () {
		$("#" + this.containerId + " .tweetsHolder").fadeIn(2000);
		});
	}
}	


TwitterDisplay.prototype.displayTweets = function(json, status) {

		var jsonRoot = json;
		var container = $("#" + this.containerId);
		
		if(json.error) {
			container.html(json.error);
			return;
		}
		if(json.results) {
			json = json.results;
		} else if(json[0].user && json[0].user.statuses_count) {
			this.totalPages = Math.ceil(json[0].user.statuses_count/this.resultsPerPage);
		}
		container.html("");
		var usedCriteria = unescape(this.criteria);
		if(usedCriteria.indexOf("#") == 0) {
			container.append("<div class='followTag'><span class='label'>" + this.tagLabel + "</span>" 
			+ unescape(this.criteria) + "</div>");
		}
			container.append("<ul class='tweetsHolder'></ul>");
		
			holder = $("#" + this.containerId + " .tweetsHolder");
			$.each(json, function(i, item){
			
				var styleString = "";
				var userId = item.user ? item.user.screen_name : item.from_user;
				var userText = userId;
				var followText = "";
				var replyText = "";
				var retweetText = "";
				var stringItem = item.toString();
				tweet = item.text.twitterize();
				if (TwitterMap[userId]) {
					userObj = TwitterMap[userId];
					styleString = ' style="color: ' + userObj.color + ';" ';
					userText = '<a class="username"' + styleString + 'href="' + userObj.profileUrl + '">' + '@' +
					userObj.name +
					'</a>';
					
					followText = '<div class="follow">' +
					'<a target=_new href="http://twitter.com/' +
					userId +
					'">Follow ' +
					userObj.name +
					'</a></div>';
					replyText = '<div class="reply">' +
					'<a target=_new href="http://twitter.com/home/?status=@' +
					userId +
					'">' +
					'</a></div>';
					retweetText = '<div class="retweet">' +
					'<a target=_new href="http://twitter.com/home/?status=RT @' +
					userId +
					' ' +
					escape(tweet) +
					'">' +
					'</a></div>';
				}
				
				tweet = item.text.twitterize();
				holder.append("<li class=\"tweets\">" +
				
				'<div class="userInfo">' +
				userText +
				'</div>' +
				'<div class="message">' +
				tweet +
				'</div>' +
				"<div class='created'" +
				styleString +
				">... " +
				item.created_at.fixTwitterDateString() +
				"</div>" +
				followText +
				replyText +
				retweetText +
				"</li>");
			});		
		if (jsonRoot.previous_page) {
			this.prevPageUrlSuffix = jsonRoot.previous_page;
			this.setPrevNavigation(true);
			
		} else if(this.operation == 'statuses' && this.currentPage > 1) {
			this.prevPageUrlSuffix = "?page=" + (this.currentPage - 1) + "&count=" + this.resultsPerPage;
			this.setPrevNavigation(true);
			
		} else {
			this.prevPageUrlSuffix = "";
			this.setPrevNavigation(false);
		}
		
		if (jsonRoot.next_page) {
			this.nextPageUrlSuffix = jsonRoot.next_page;
			this.setNextNavigation(true);
			
		} else if(this.operation == 'statuses' && this.currentPage < this.totalPages) {
			this.nextPageUrlSuffix = "?page=" + (this.currentPage + 1) + "&count=" + this.resultsPerPage;
			this.setNextNavigation(true);
			
		} else {
			this.nextPageUrlSuffix = "";
			this.setNextNavigation(false);
		}
		
}

TwitterDisplay.prototype.displayTweetsPix = function(json, status) {

		var jsonRoot = json;
		var container = $("#" + this.containerId);
		
		if(json.error) {
			container.html(json.error);
			return;
		}
		if(json.results) {
			json = json.results;
		} else if(json[0].user && json[0].user.statuses_count) {
			this.totalPages = Math.ceil(json[0].user.statuses_count/this.resultsPerPage);
		}
		container.html("");
		var usedCriteria = unescape(this.criteria);
		if(usedCriteria.indexOf("#") == 0) {
			container.append("<div class='followTag'><span class='label'>" + this.tagLabel + "</span>" 
			+ unescape(this.criteria) + "</div>");
		}		
		
		container.append("<ul class='members'></ul>");
		
		holder = $("#" + this.containerId + " .members");		
			$.each(json, function(i, item){
				var styleString = "";
				var userId= "";
				userId = item.user ? item.user.screen_name : item.from_user;
				var photoImageSrc="";
				var photoImageSrcNew="";
				photoImageSrc = item.profile_image_url;
				var slashpoint=photoImageSrc.lastIndexOf("/");
				var uspoint=photoImageSrc.lastIndexOf("_");
				var dotpoint=photoImageSrc.lastIndexOf(".");
				var srcLength=photoImageSrc.length;
				var thumbSize="_bigger";
				var imgPath_1=photoImageSrc.substring(0,slashpoint);
				var imgPath_2=photoImageSrc.substring(slashpoint,uspoint);
				var imgPath_3=photoImageSrc.substring(dotpoint,(srcLength));
				photoImageSrcNew=imgPath_1+imgPath_2+thumbSize+imgPath_3;
				
				styleString="background: transparent url("+photoImageSrcNew+") no-repeat scroll center center";
				var avatarAnc="<a target='_new' href='http://twitter.com/"+userId+"'><img src='"+photoImageSrcNew+"'></a>";
				var avatarText="<div style='"+styleString+"'>"+avatarAnc+"</div>";
				var userText = "<div class='title'><h4><a href='http://twitter.com/"+userId+"'>"+userId+"</a></h4></div>";
				holder.append("<li class=\"member compact m\">" +
				
				'<div class="avatar">' +
				avatarText +
				'</div>' +
				'<div class="txt">' +
				userText +
				'</div>'+
				"</li>");
			});			
		
		if (jsonRoot.previous_page) {
			this.prevPageUrlSuffix = jsonRoot.previous_page;
			this.setPrevNavigation(true);
			
		} else if(this.operation == 'statuses' && this.currentPage > 1) {
			this.prevPageUrlSuffix = "?page=" + (this.currentPage - 1) + "&count=" + this.resultsPerPage;
			this.setPrevNavigation(true);
			
		} else {
			this.prevPageUrlSuffix = "";
			this.setPrevNavigation(false);
		}
		
		if (jsonRoot.next_page) {
			this.nextPageUrlSuffix = jsonRoot.next_page;
			this.setNextNavigation(true);
			
		} else if(this.operation == 'statuses' && this.currentPage < this.totalPages) {
			this.nextPageUrlSuffix = "?page=" + (this.currentPage + 1) + "&count=" + this.resultsPerPage;
			this.setNextNavigation(true);
			
		} else {
			this.nextPageUrlSuffix = "";
			this.setNextNavigation(false);
		}
		
}
 

TwitterDisplay.prototype.setNextNavigation = function(enabled) {

	var id = "#" + this.containerId + "Next";
	if(enabled) {
		$(id).removeClass('tcNextDisabled');
		$(id).addClass('tcNextEnabled');
		$(id).attr('href', '#');
	} else {
		$(id).removeClass('tcNextEnabled');
		$(id).addClass('tcNextDisabled');
		$(id).attr('href', 'javascript:void(0)');
	}
}


TwitterDisplay.prototype.setPrevNavigation = function(enabled) {

	var id = "#" + this.containerId + "Prev";
	if(enabled) {
		$(id).removeClass('tcPreviousDisabled');
		$(id).addClass('tcPreviousEnabled');
		$(id).attr('href', '#');
	} else {
		$(id).removeClass('tcPreviousEnabled');
		$(id).addClass('tcPreviousDisabled');
		$(id).attr('href', 'javascript:void(0)');
	}
}


function delegateTwitterCallback (twitterDisplay, json, status) {
	twitterDisplay.displayTweets(json, status);
}

function delegateTwitterCallbackForPix (twitterDisplay, json, status) {
	twitterDisplay.displayTweetsPix(json, status);
}
 

        
String.prototype.twitterize = function() {
	
    var tweet = this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(str){
        return '<a class="extLink" target=_new href="' + str + '">' + str + '</a>';
    });
	
    tweet = tweet.replace(/([@])([\w]+)/g, '$1<a class="twitterLink" target=_new href="http://twitter.com/' + '$2'.toLowerCase() + '">$2</a>');
	
	
	return tweet;
};

String.prototype.fixTwitterDateString = function() {
	
    var dateArray = this.split(" ");
    var tweetDateString;

    if(parseInt(dateArray[1], 10) > 0) {
   	tweetDateString = dateArray[2] + " " + dateArray[1] + ", " + dateArray[3] + " " + dateArray[4];
    } else {
 	tweetDateString = dateArray[1] + " " + dateArray[2] + ", " + dateArray[5] + " " + dateArray[3];
    }

    var tweetTime = Date.parse(tweetDateString);
    var currDate = new Date();
    
    var timeDiff = parseInt(currDate.getTime() - tweetTime) / 1000;
    timeDiff = timeDiff + (currDate.getTimezoneOffset() * 60);               
	
	var formattedString = '';
    if (timeDiff < 60) {
        formattedString = 'a minute ago';
    }
    else if (timeDiff < (45 * 60)) {
        formattedString = Math.round(timeDiff / 60) + ' minutes ago';
    }
    else if (timeDiff < (1.5 * 60 * 60)) {
        formattedString = '1 hour ago';
    }
    else if (timeDiff < (24 * 60 * 60)) {
   	formattedString = Math.round(timeDiff / (60 *60)) + ' hours ago';
    }
    else if (timeDiff < (1.5 * 24 * 60 * 60)) {
      	formattedString = '1 day ago';
    }
    else if (timeDiff < (7 * 24 * 60 * 60)) {
      	formattedString = Math.round(timeDiff / (24 * 60 * 60)) + ' days ago';
    }
    else if (timeDiff < (1.5 * 7 * 24 * 60 * 60)) {
       	formattedString = '1 week ago';
    }
    else if (timeDiff < (4 * 7 * 24 * 60 * 60)) {
	formattedString = Math.round(timeDiff / (7 * 24 * 60 * 60)) + ' weeks ago';
    }
    else if (timeDiff < (1.5 * 4 * 7 * 24 * 60 * 60)) {
	formattedString = '1 month ago';
    }
    else if (timeDiff < (12 * 4 * 7 * 24 * 60 * 60)) {
	formattedString = Math.round(timeDiff / (4 * 7 * 24 * 60 * 60)) + ' months ago';
    }
    else if (timeDiff < (1.5 * 12 * 4 * 7 * 24 * 60 * 60)) {
	formattedString = '1 year ago';
    } 
    else if (timeDiff > (1.5 * 12 * 4 * 7 * 24 * 60 * 60)) {
	formattedString = Math.round(timeDiff / (12 * 4 * 7 * 24 * 60 * 60)) + ' years ago';
    }
    else {
	formattedString = tweetDateString;
    }
    return formattedString;
}




/** Twitter Reply Methods **/

    $.urlParam = function(name){
        var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null) {
            return "";
        }
        else {
            return results[1];
        }
    }
    
    
    function showTwitterReplyBox(author){
    
    
        createCookie("t_author", author);
        if (author) {
            $("#twitterReplyContainer #msg").val("@" + author + " ");
            
        }

	twitter_url = twitter_3oh3_url + "?verify=" + true + "&oauth_token=" + oauth_token + "&jsoncallback=?";
	
	$.getJSON(twitter_url, function(data){
	    if (data.request_link) {
	    	$("#twitterReplyContainer").show();
		$("#twitterReplyContainer #container").show();
		$("#twitterReplyContainer #welcome").show();
		$("#twitterReplyContainer #msg").hide();
		$("#twitterReplyContainer #replyButton").hide();
		$("#twitterReplyContainer #container").html("<a class='SignIn' href='" + data.request_link + "'>Sign in with Twitter</a>");
            } else {
            	$("#twitterReplyContainer #container").hide();
	    $("#twitterReplyContainer").show();
	    $("#twitterReplyContainer #msg").show();
	    $("#twitterReplyContainer #replyButton").show();
	    $("#twitterReplyContainer #welcome").hide();
        	$("#twitterReplyContainer #msg").focus();
        	$("#twitterReplyContainer #response").hide();
            
            }

    	});
    }
    
    
function closeTwitterReplyBox(speed){
	if (speed) {
		$("#twitterReplyContainer").fadeOut(speed);
	}
	else {
		$("#twitterReplyContainer").hide();
	}
	eraseCookie("t_author");
}

    
function submitToTwitterJSON(){

	var msg = escape(jQuery.trim($("#twitterReplyContainer #msg").val()));

	if(msg) {

		twitter_url = twitter_3oh3_url + "?message=" + msg + "&oauth_token=" + oauth_token + "&jsoncallback=?";
	} else {
		twitter_url = twitter_3oh3_url + "?jsoncallback=?";        
	}


	$.getJSON(twitter_url, function(data){
	    if (data.request_link) {
		$("#twitterReplyContainer #container").show();
		$("#twitterReplyContainer #welcome").show();
		$("#twitterReplyContainer #msg").hide();
		$("#twitterReplyContainer #replyButton").hide();
		$("#twitterReplyContainer #container").html("<a class='SignIn' href='" + data.request_link + "'>Sign in with Twitter</a>");
	    } else {
		$("#twitterReplyContainer #container").hide();
		$("#twitterReplyContainer #welcome").hide();
		$("#twitterReplyContainer #msg").hide();
		$("#twitterReplyContainer #replyButton").hide();
		if (data["user"]) {
		    $("#twitterReplyContainer #response").html("<span class='success'>Thanks! Your reply will appear on the site shortly.</span>");
			setTimeout("closeTwitterReplyBox('slow')",3000);
		} else if (data.error) {
			$("#twitterReplyContainer #response").html("<span class='failure'>We are having problems connecting to Twitter right now. Please try again later.</span>");
		} else {
			$("#twitterReplyContainer #response").html("<span class='failure'>We are having problems connecting to Twitter right now. Please try again later.</span>");
		}
		$("#twitterReplyContainer #response").show();
	    }
	});

}
