var instance = null;
var doStream = 1;
var Streaming = {
	options: [],
	auctions: [],
	auctionsData: [],
	focus:    [],
	streamingMessage: '',
	url: '',
	jsonString: '',
	lastUpdate: null,
	instance: null,

	setStreamingMessage: function(msg) {
		this.streamingMessage = msg;
	},

	add: function(url, auctionId, time, bid, bidder, nextBid) {
		this.options[auctionId] = [time, bid, bidder, nextBid, false];
		this.auctions.push(auctionId);

		if(!this.url)
		this.url = url;

		Event.observe(nextBid, 'focus', function () {
			this.options[auctionId][4] = true;
		}.bind(this));
		Event.observe(nextBid, 'blur', function () {
			this.options[auctionId][4] = false;
		}.bind(this));

	},

	/*add : function(auctionId, timeleft) {
		this.auctions.push(auctionId);
		this.auctionsData.push({id: auctionId, timeleft: timeleft});
		//this.auctionsData.push(id: auctionId, time: timeleft));
	},*/

	request: function() {

		this.jsonString = this.auctions.join(",");
		instance = new Ajax.PeriodicalUpdater('notExistingId', this.url, {
			onSuccess: function(t){
				this.success(t);
			}.bind(this),
			method: 'post',
			//parameters: 'auctions='+this.jsonString+'&time='+this.lastUpdate,
			parameters: 'json='+this.jsonString,
			evalJSON: false,
			frequency: 1
		});
	  if(!doStream) instance.stop();

	  window.doStream = doStream;
	  window.setTimeout(function() {

			var baseUrl = this.url.replace(/auctions\/updateJson/g, 'products/streaming');
			successUrl = baseUrl + "/doStream/0";

			new Ajax.Request(successUrl, {
				method: 'get',

				onSuccess: function(t) {
					 $('streamingContainer').update('Streaming OFF');
					 instance.stop();
					 window.doStream = false;
					 if(!window.doStream && this.streamingMessage) {

					 	var c = confirm(this.streamingMessage);
					 	if(c) {
					 		$('streamingContainer').update('Streaming ON');
							instance.start();
							window.doStream = true;
							new Ajax.Request(baseUrl + '/doStream/1', { method: 'get'});
					 	}
					 }

				}.bind(this)
			});

			// 20 minutes
		}.bind(this),  20 * 60 * 1000);

	},

	success: function(req) {
		/*if (req.responseText == '[]') {
			return false;
		} else {
			//alert(req.responseText);
			instance.stop();
		}

		this.data = JSON.parse(req.responseText);

		if (!this.data) {
			return false;
		}
		alert(this.data);
		instance.stop();

		for (i in this.data) {
		    var item = this.data[i];
		    var element = jQuery('.item_'+item.id);
		    jQuery(element).find('.bid_area')
		        .animate({ 'opacity' : 0 }, { duration: 'fast' })
		        .animate({ 'opacity' : 100 }, { duration: 'fast' });
		    jQuery(element).find('.bid_user')
		    	.html(item.bid.user);
		    jQuery(element).find('.bid_time').html(item.time_left);
		    jQuery(element).find('.price1').html(item.bid.price);
		}

		//OLD CODE BELOW
		return;
		*/

		var id = '';
		this.data = JSON.parse(req.responseText);
		var regex = /00:00/;

		 for(i in this.data) {

		 	id = parseInt(i.replace(/r/, ''));

		 	if(this.options[id]) {
		 		// update the time, 0 index is the DOM ID
			 if($(this.options[id][0]) && this.options[id][0] !== '') {
		 		$(this.options[id][0]).update(this.data[i].t);

		 		if(parseInt(this.data[i].th) == 1) {
		 			new Effect.Highlight(this.options[id][0], { duration: 3});
		 			$(this.options[id][0]).className += ' important';

		 			if(this.data[i].t.match(regex)) {
		 				$$('#item_'+id+' .button')[0].hide();

		 				if($$('#item_'+id+' .button')[1]) {
		 					$$('#item_'+id+' .button')[1].hide();
		 				}

		 				if($('bid_'+id)){
		 					$('bid_'+id).parentNode.hide();
		 				}
			 			  if($$('#item_'+id+' .float_left')[0]) {
			 				$$('#item_'+id+' .float_left')[0].hide();
			 				$$('#item_'+id+' .float_left')[1].hide();
			 			  }

		 				// update Time with the status
		 				if(this.data[i].s) {
		 					$(this.options[id][0]).update(this.data[i].s);
		 				}
		 			}

		 		} else {
		 			$(this.options[id][0]).className = '';
		 		}

			 }
		 		if(this.data[i].b && $(this.options[id][1]) && $(this.options[id][1]).innerHTML !== this.data[i].b) {

			 			$(this.options[id][1]).update('');
			 			$(this.options[id][1]).update(this.data[i].b);

                                                $$('#item_'+id+' .price2 .button')[0].addClassName('reset');

				 		/*var txtNode = document.createTextNode(this.data[i].b);

			 			$(this.options[id][1]).appendChild(txtNode);*/
			 			new Effect.Highlight(this.options[id][1], { duration: 3});

		 		}



		 		if(this.data[i].u && $(this.options[id][2])) {
		 			var usernameNode = $$('#'+this.options[id][2] + ' span')[0];
		 	 		var usernameValue = usernameNode.innerHTML;

		 				$(this.options[id][2]).update('');
			 			// update the user flag
				 		if(this.data[i].f) {
					 		var flag = new Image();
					 	 	flag.src = 'http://jewellery-bidding.eu/pics/lang/'+this.data[i].f;
					 		//flag.src = 'http://localhost/bidz/web/pics/lang/'+this.data[i].f;
					 		flag.setAttribute('class', 'user_flag');
					 		$(this.options[id][2]).appendChild(flag);
				 		}
				 		var txtNode = document.createTextNode(this.data[i].u);
				 		var spanContainer = new Element('span', {className: 'bid_username'});
				 		spanContainer.appendChild(txtNode);
			 			$(this.options[id][2]).appendChild(spanContainer);

					if(this.data[i].u != usernameValue)
			 			new Effect.Highlight(this.options[id][2], { duration: 3});

		 		}


		 		// update the next bid if the next bid is different from the current on the page and if the the field is not on focus
		 		if(this.data[i].n && $(this.options[id][3]) && this.data[i].n !== $(this.options[id][3]).value && !this.options[id][4]) {
		 			$(this.options[id][3]).value = this.data[i].n;
		 		}

		 	}
		 }
	},

	setUrl : function(url) {
		this.url = url;
	},

	timersUpdate: function() {
		//this.instance.stop();
		for (i in this.auctionsData) {
		    var item = this.auctionsData[i];
		    jQuery('.item_'+item.id)
		      .find('.bid_time span')
		      .html(item.timeleft);
		}
	},

	initialize : function() {
		this.lastUpdate = Date.parse(new Date())/1000; //To unix timestamp
		//this.instance = setTimeout(this.timersUpdate, 1000);
		if (this.auctions.length >0 ) {
		  this.request();
		}
	}

};



