;(function($) {

	$.fn.HotJobs = function(settings){

		settings = jQuery.extend({
			pause: 3500,
			duration: 1000,
			easing: 'swing',
			channel: 0
		}, settings);

		this.each(function() {

			function swap() {
				$("div.oSidebarHotJob:last",obj).clone().hide().prependTo("div.oSidebarHotJobHolderInner",obj);
				$("div.oSidebarHotJobHolderInner",obj).css('bottom','0px');
				$('div.oSidebarHotJob:last-child',obj).remove();
				$('div.oSidebarHotJob:last', obj).prev().fadeIn('100', function() {
					timeout = setTimeout(function(){ animate(); }, settings.pause);
				}); //show bottom two then kick start timer for the next one.
			};

			function animate() {
				$("div.oSidebarHotJobHolderInner",obj).animate(
					{ bottom: '-57px' },
					{ queue:false, duration:settings.duration, easing:settings.easing, complete:swap }
				);
			};

			//setup
			var obj = $(this);
			if (settings.channel!=0) {
				$.getJSON('hotjobs.php?ch='+settings.channel, function(data) {
					if (data.length>0) {
						//generate container.
						var htmlsnippet = "<div class=\"oSidebarHotJobHolder";
						if (obj.hasClass('oHomeHotspot')) { htmlsnippet+=" wide"; }
						htmlsnippet+= "\" />";

						var holder = $(htmlsnippet).appendTo(obj);
						var container = $("<div class=\"oSidebarHotJobHolderInner\" />").appendTo(holder);
						$.each(data, function(i,item) {
							$(container).append("<div class=\"oSidebarHotJob\" style=\"display: none;\"><span class=\"oSidebarHotJobTitle\">"+item.jobtitle+"</span><span class=\"oSidebarHotJobLocation\">"+item.location+"</span><span class=\"oSidebarHotJobLink\"><a href=\""+item.url+"\">Find out more</a></span></div>");
						});
						$('div.oSidebarHotJob:last', obj).show().prev().show(); //show bottom two

						if (data.length==1) { //only one job, make sure its aligned top.
							$("div.oSidebarHotJobHolderInner",obj).css('bottom','57px');
						}

						if (data.length>2) { //if more than two, animate.
							//init
							var timeout = setTimeout(function(){ animate(); }, settings.pause);
						}
					}
				});
			}
		});
	};
})(jQuery);

$(document).ready(function() {
	$('#oSidebarHotJobs').HotJobs({channel: hj_channel});
	$('div.oHomeHotspot.pharmacy-jobs').HotJobs({channel: hj_channel});
	$('div.oHomeHotspot.stores-jobs').HotJobs({channel: hj_channel});
	$('div.oHomeHotspot.opticians-box-1').HotJobs({channel: hj_channel});
});
