/**
 * FXTimes Live Event, js-injection script to get events from fxtimes.com
 *
 * @author Ivan Garmatenko <igarmatenko@vtsystems.com>
 * $Id: FXTimesLiveEvents.js,v 1.3 2009/11/20 13:06:12 ashevlyakov Exp $
 */

if (typeof jQuery.FXTimesLiveEvent == 'undefined') {
	jQuery.fn.extend({
		FXTimesLiveEvent: function(lazyOptions) {

			var options = jQuery.extend({}, jQuery.FXTimesLiveEvent.defaults, lazyOptions);
			options.callback_id = generateId();

			function generateId() {
				var newDate = new Date;
				return 'live_event_' + newDate.getTime();
			}

			return jQuery.FXTimesLiveEvent.instances[options.callback_id] = new jQuery.FXTimesLiveEvent(this, options);
		}
	});

	jQuery.FXTimesLiveEvent = function(object, options) {

		periodicallyRequest(options.request_url, options.request_interval, {
			callback_id: options.callback_id,
			homestraight_time: options.homestraight_time
		});

		function periodicallyRequest(url, interval, data) {
			oneTimeRequest(url, data);
			setInterval(function() {
				jQuery.get(url, data, {}, 'jsonp');
			}, toMiliSeconds(interval));
		}

		function oneTimeRequest(url, data) {
			jQuery.get(url, data, {}, 'jsonp');
		}

		function hasNoLiveEvent(data) {
			if (!data.text || !data.type) return true;
			return (data == '' || data == false);
		}

		function hasEventInFuture(data) {
			if (hasNoLiveEvent(data)) return true;
			return (data.type == 'future');
		}

		function isNoNeedToShow(data) {
			return hasEventInFuture(data);
		}

		function draw(data) {
			var	liveEventContainer = jQuery(object);

			liveEventContainer
				.addClass("liveEventBanner-" + data.group)
				.attr({
					onclick: "location.href = '" + data.url + "'",
					title: data.title
				});


			drawTextBlock(liveEventContainer, options.text_block_selector, data);
			return liveEventContainer.show();
		}

		function drawTextBlock(liveEventContainer, textBlockSelector, data) {

			if (textBlockSelector && textBlockSelector != "") {

				liveEventContainer.find(textBlockSelector).html(
					jQuery('<a>')
						.attr({href: data.url, title: data.title})
						.addClass(data.type)
						.addClass('countdown')
						.append(jQuery('<em>').html('Live:'))
						.append(jQuery('<strong>').html(data.text))
				);
			}
		}

		function toMiliSeconds(seconds) {
			return seconds * 1000;
		}

		return {
			load: function(data) {
				if (isNoNeedToShow(data)) return jQuery(object).hide();
				return draw(data);
			}
		};
	}

	jQuery.FXTimesLiveEvent.instances = [];

	jQuery.FXTimesLiveEvent.defaults = {
		request_url: 'http://fxtimes.com/services/live-events.json',
		request_interval: 6,
		homestraight_time: "60 min",
		text_block_selector: ""
	};

	jQuery.FXTimesLastLiveEvent = function(data) {
		var callbackId = data.callback_id;
		if (callbackId) jQuery.FXTimesLiveEvent.instances[callbackId].load(data);
	}
}