// include only once
if (typeof handleTwitters != 'function') (function () {
	window.handleTwitters = function (obj, options) {
		var objCount = obj.results.length, twitterData = new String("{results:["), ReTweets = new RegExp("^RT:? ", ""), trueCount = 0;

		// Format the data that needs to be sent back to the server in json format.
		for (var i = 0; i < objCount; i++) {
			// ignore retweets
			if (ReTweets.test(obj.results[i].text)) continue;
			twitterData = twitterData + "{";
			twitterData = twitterData + "text:\"" + removeLinks(obj.results[i].text).replace("\"", "\\\"") + "\",";
			twitterData = twitterData + "from_user:\"" + obj.results[i].from_user + "\",";
			twitterData = twitterData + "id:" + obj.results[i].id + ",";
			twitterData = twitterData + "created_at:\"" + obj.results[i].created_at + "\"";
			twitterData = twitterData + "}";
			if (i < (objCount - 1)) twitterData = twitterData + ",";
			trueCount++;
		}
		twitterData = twitterData + "]}";

		// Post the data to the server with ajax.
		$.ajax({
			type: "post",
			url: "http://www.ez-tracks.com/twitter/storetwitter.html",
			data: {twitterData:twitterData, QueryLevel:options.querylevel, ContentID:options.ContentID, ContentType:options.ContentType, HowMany:options.HowMany, SourceTypeID:2},
		});
	};

	window.getTwitters = function (options) {
		// Default the options.
		if (!options) {
			options = {};
		}

		if (!options.query) options.query = "";
		if (!options.querylevel) options.querylevel = 0;

		if (!options.ContentID) options.ContentID = 0;
		if (!options.ContentType) options.ContentType = "";
		if (!options.HowMany) options.HowMany = 0;

		if (!options.lang) options.lang = "en";

		if (!options.since_id) options.since_id = 0;

		window['twitterCallback'] = function (obj) {
			handleTwitters(obj, options);
		};

		// This code gets the data from twitter once the DOM is ready.
		$(document).ready((function(options) {
			return function () {
				if (options.query == "" || options.querylevel == 0 || options.ContentID == 0 || options.ContentType == "") {
					return;
				}

				var url = 'http://search.twitter.com/search.json?q=' + options.query + '&callback=twitterCallback' + '&lang=' + options.lang + (options.since_id > 0 ? ('&since_id=' + options.since_id) : "");

				var script = document.createElement('script');
				script.setAttribute('src', url);
				document.getElementsByTagName('head')[0].appendChild(script);
			};
		})(options));
	};

	// Remove the links before sending to the server.  If we do this here, less data will be sent to the server.
	function removeLinks(s) {
		return s.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) {
			return "...";
		}).replace(/[wW]{3}.[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) {
			return "...";
		});
	}
})();