$(function () {
window.apeClient = (function () { 
	var client = new APE.Client;
	
	// list of channels to join
	var channels = [];
	
	// Collect a list of channels to subscribe to
	if (LiveHaggleData && LiveHaggleData.length > 0) {
		debugMsg("Found " + LiveHaggleData.length + " auctions");
		for (x=0; x<LiveHaggleData.length; x++) {
			channels.push('*lh' + LiveHaggleData[x].AuctionID + "b");
		}
	}
	if (typeof sb != 'undefined' && typeof sb.blink != 'undefined') {
		// blink is loaded, check for a list of channels to join.
		if (sb.blink.toJoin.length > 0) {
			channels = channels.concat(sb.blink.toJoin);
		}
	}
	console.log('Channels to join: ', channels);
	
	function debugMsg(text) {
		$('#debug').append(text + "\n\n");
		//alert(text);
	}
	
	function blinkLHMenu () {
		try {
			if ($('.lhMenu').data('blinker') && $('.lhMenu').data('blinker') != null)
				return;
		} catch (e) {
			alert("blinkLHMenu()1:" + e.message);
		}
		
		try {
			p = $('.lhMenu').offset();
			blinker = $('<div />')
				.css({
					backgroundColor : 'red',
					width : 88 + 'px',
					height : 30 + 'px',
					position : 'absolute',
					top : (p.top + 7) + 'px',
					left : p.left + 'px',
					opacity : 0,
					zIndex : 99 })
				.animate({opacity:1},{duration:400, complete:function () { $(this).animate({opacity:0},{duration:400, complete:function () { $(this).remove(); $('.lhMenu').data('blinker', null) } }); }});
			$('.lhMenu')
				.css({zIndex:100,position:'relative'})
				.data('blinker', blinker);
			$(blinker).appendTo('body');
		} catch (e) {
			alert("blinkLHMenu()2:" + e.message);
		}
	}
	
	function updateLHInfo (data) {
		try {
			$('.LHInfo .bid').text(data['BidPrice']);
			$('.LHInfo .bids').text(data['BidCount']);
			$('.LHInfo .winning').text( data['UserID'] == LoginID ? "Yes" : "No" );
		} catch (e) {
			alert("updateLHInfo()1:" + e.message);
		}
		/*
			{
			 'BidID' => 138,
			 'AuctionID' => 4,
			 'UserID' => 83,
			 'Username' => 'Alex',
			 'BidPrice' => '130000',
			 'BidCount' => 89
			}
			DumperAlert(data);
		*/
	}
	
	// set to false to disable debugging
	var debug = true;
	client.addEvent('load', function() {
		//3) Call core start function to connect to APE Server
		debugMsg('client loaded');
		client.core.start();
	});
	
	client.addEvent('ready', function(a) {
		debugMsg('Your client is now connected');
	});
	
	client.addEvent('restoreEnd', function(a) {
		// Send our PHP Session details
		if (typeof phpSessionID != 'undefined') {
			this.core.request.send('phpsession', {id: phpSessionID});
		}
		
		// part inappropriate channels
		this.core.partAllExcept(channels);
		
		// join the channels
		//this.core.join(channels);
	});
	client.addEvent('init', function() {
		var core = this.core;
		
		core.channelNames = function () {
			var	pipes	= core.pipes.getValues(),
				chans	= [];
				
			for (var i=0; i<pipes.length; i++) {
				chans.push(pipes[i].name);
			}
			
			return chans;
		};
		core.findChannel = function (name) {
			var	pipes	= core.pipes.getValues();
			
			for (var i=0; i<pipes.length; i++) {
				if (pipes[i].name == name) {
					return pipes[i];
				}
			}
			
			return null;
		};
		core.partAllExcept = function (channels) {
			var	pipes = core.pipes.getValues(),
				d = channels.length,
				c = pipes.length,
				part = [],
				x = 0;
			
			for (var i=0; i<c; i++) {
				var	keep = false;
				for (var o=0; o<d; o++) {
					if (pipes[i].name == channels[o])
						keep = true;
				}
				if (!keep) {
					console.log('Paring: ', pipes[i].name);
					core.request.stack.add('LEFT', { "channel":pipes[i].name });
					x++;
				}
			}
			for (var i=0; i<d; i++) {
				var join = true;
				for (var o=0; o<c; o++) {
					if (pipes[o].name == channels[i])
						join = false;
				}
				if (join) {
					core.request.stack.add('JOIN', { "channels":channels[i] });
					x++
				}
			}
			console.log('Got ', x, ' requests stacked');
			if (x > 0)
				core.request.stack.send();
		};
		
		//client.core.join(['*auction4','*auction5']);
		//$('body')[0].apeInit = this;
	});
	pipeCreate = function (pipe, options) {
		debugMsg("(pipeCreate) " + pipe);
		$('body')[0].ApePipe = pipe;
		$.cookie('APE_PubID', apeClient.core.getPubid());
		//Dumper(options);
	}
	
	
	setup = function(type, pipe, options){
		//DumperAlert([type, pipe, options]);
		//pipe.send("(setup) hello");
	};
	
	gotRaw = function(raw, pipe){
		//alert(raw.data.msg);
		//this.writeMessage(pipe, raw.data.msg, raw.data.sender);
	}
	
	gotChat = function(raw, pipe){
		//alert(raw.data.msg);
		
		try {
			if ($('#LH' + raw.data.AuctionID).length > 0) {
				$('#LH' + raw.data.AuctionID).data('logic').NewChat(raw.data);
			} else {
				blinkLHMenu();
			}
			
			//debugMsg(Dumper(raw));
		} catch (e) {
			alert("gotChat()1:" + e.message);
		}
		
		try {
			var auctionData = FindAuction(raw.data.AuctionID);
			if (auctionData) {
				if (auctionData.dump) {
					auctionData.dump.chat.push({
							'ChatText' 		: raw.data.ChatText,
							'name'			: raw.data.name,
							"ChatterID"		: raw.data.ChatterID,
							"ChatterType"	: raw.data.ChatterType,
							"ChatDateTime"	: raw.data.ChatDateTime,
							"fullTime"		: raw.data.fullTime
					   });
				}
			}
		} catch (e) {
			alert("gotChat()2:" + e.message);
		}
	};
	
	gotBlink = function(raw, pipe) {
		console.log('GOT BLINK!', raw);
		var b = new sb.blink(raw.data.blink);
		b.refresh(raw.data);
	};
	
	gotBid = function(raw, pipe){
		try {
			var auctionData = FindAuction(raw.data.AuctionID);
			if (auctionData) {
				auctionData['bids'] = raw.data.BidCount;
				auctionData['MaxBidPrice'] = raw.data.BidPrice;
				auctionData['bidder'] = raw.data.UserID;
				auctionData['bidderName'] = raw.data.Username;
			
				if (auctionData.dump) {
					auctionData.dump['bidders'] = raw.data.BidderCount;
					auctionData.dump.bids.push({
							'BuyerID' 		: raw.data.UserID,
							'BuyerBidPrice' : raw.data.BidPrice,
							'name' 			: raw.data.Username
					   });
				}
			}
		} catch (e) {
			alert("gotBid()2:"  + e.message);
		}
		
		try {
			if ($('#LH' + raw.data.AuctionID).length > 0) {
				$('#LH' + raw.data.AuctionID).data('logic').NewBid(raw.data);
			} else {
				blinkLHMenu();
			}
			updateLHInfo(raw.data);
		} catch (e) {
			alert("gotBid()1:"  + e.message);
		}
	};
	
	gotStup = function (raw, pipe) {
		/*{
			'time' => '1257189064',
			'raw' => 'stup',
			'data' => {
					'cmd' => 'CloseTB'
				   }
		}*/
		if (raw.data.cmd == "CloseTB") {
			tb_remove();
		} else if (raw.data.cmd == "ReloadPage") {
			window.location.reload();
		} else if (raw.data.cmd == "FBCNewUser") {
			fb_login_complete(true);
		} else {
			//DumperAlert(raw);
		}
	};

	function errBadSessId ()
	{
		initApe();
	};
	
	function initApe () {
		// load the APE client
		try {
			console.log('Passing in channels: ', channels);
			client.load({
				'domain': APE.Config.domain,
				'server': APE.Config.server,
				'identifier': 'jquery',
				'channel': channels,
				'complete': function(ape){ 
					ape.addEvent('pipeCreate', setup);
					ape.addEvent('uniPipeCreate', pipeCreate);
					ape.addEvent('multiPipeCreate', pipeCreate);
					ape.onRaw('data', gotRaw);
					ape.onRaw('chat', gotChat);
					ape.onRaw('blink', gotBlink);
					ape.onRaw('bid', gotBid);
					ape.onRaw('stup', gotStup);
					ape.onError('004', errBadSessId);
					// APE has finished loading so now we can load our scripts
					
					// colorChanger(ape [obj], debug [bool]);
					//new colorChanger(ape, debug).initialize();
					//alert(ape);
					//window.client = ape;
					
					//ape.addEvent('pipeCreate', function (type, pipe, options){ window.pipe = pipe; });
					
					if(debug)
						$("#debug").append("<span><strong>APE has finished loading</strong></span><br />");
				},
				'scripts': APE.Config.scripts //Scripts to load for APE JSF
			});
		} catch (e) {
			console.log('initApe()', e);
		}
	};
	initApe();
	
	return client;
})();
});