// BUSINESS THEME
creativeway.elements = {};

$('body').bind('creativeway.pageReady', function() {
	creativeway.initTicker();
	creativeway.listenForUpdates();

	// fetch the first set of results
	$('body').trigger('creativeway.onCoursesChange');
});

creativeway.initTicker = function() {
	creativeway.digits = {
		current: 0,
		target: 0,
		width: 57,
		top: { height: 31 },
		bottom: { height: 35 },
		animations: [],
		infinite: false,
		requests: [],
		lastrequest: null
	};

	creativeway.elements['numCourses'] = $('#number-of-courses');
	creativeway.elements['numCourses'].html('\
		<div title="0"><span></span><span></span></div>\
		<div title="0"><span></span><span></span></div>\
		<div title="0"><span></span><span></span></div>');

	creativeway.elements['numCourses'].find('div').each(function(i, o) {
		$(o).find('span:eq(0)').css({backgroundImage: 'url(/images/themes/business/numbers/business-numbers-sprite.png)', top:0, height:creativeway.digits.top.height});
		$(o).find('span:eq(1)').css({backgroundImage: 'url(/images/themes/business/numbers/business-numbers-sprite.png)', backgroundPosition: '0 -'+creativeway.digits.top.height+'px', top:creativeway.digits.top.height, height:creativeway.digits.bottom.height});
	});
};

creativeway.listenForUpdates = function() {
  $('body').bind('creativeway.onCoursesChange', function() {
    $("ul.checkboxes li :checkbox").parent().removeClass("selected");
    $("ul.checkboxes li :checkbox:checked").parent().addClass("selected");
    var levelChecked = $(".column-level :checkbox:checked").length;
    var areaChecked = $(".column-area :checkbox:checked").length;
    if (areaChecked && levelChecked) {
      $("#number-of-courses-text").fadeOut();
      $("#number-of-courses").fadeIn();
      $(".column-course input").fadeIn();
      if (creativeway.digits.requests.length < 1) {
        creativeway.digits.current = creativeway.digits.target;
        creativeway.digits.infinite = true;
        creativeway.animateTicker();
      }

      creativeway.digits.requests.push(Math.floor(Math.random()*100000));

      creativeway.digits.lastrequest = $.getJSON($('#coursesform').attr('action')+'.json', $('#coursesform').serialize(), function(data) {
        creativeway.digits.requests.pop();

        if (creativeway.digits.requests.length < 1 && data) {
          creativeway.updateTicker(data.number);
          if (data.number === 0 ) {
            $(".column-course input").addClass("disabled").attr("disabled", "disabled");
          } else {
            $(".column-course input").removeClass("disabled").removeAttr("disabled");
            $(".column-course input").show();
            $("#number-of-courses-text").hide();
            $("#number-of-courses").show();
          }
        }
      });
    } else {
      $("#number-of-courses").fadeOut();
      $(".column-course input").fadeOut();
      $("#number-of-courses-text").fadeIn();
    }
	});
};




/****************
*********************************/
creativeway.updateTicker = function(n) {
	creativeway.digits.animations = [];
	creativeway.digits.target = n;
	creativeway.digits.infinite = false;
	creativeway.animateTicker();
};

creativeway.animateTicker = function() {
	creativeway.digits.current = creativeway.digits.infinite ? Math.floor(Math.random()*1000) : creativeway.digits.current;

	if (creativeway.digits.current === creativeway.digits.target) {
		$('body').trigger('creativeway.onTickerUpdated');
		return false;
	}

	if (creativeway.digits.current < creativeway.digits.target) {
		creativeway.digits.current += Math.ceil((creativeway.digits.target - creativeway.digits.current) / 4);
	}
	else {
		creativeway.digits.current -= Math.ceil((creativeway.digits.current - creativeway.digits.target) / 4);
	}

	var diff = creativeway.digits.target - creativeway.digits.current;
	diff = (diff === 0) ? 1 : diff;

	var duration = creativeway.digits.infinite ? 25 : 300 / (diff);
	if (duration < 0) {
		duration -= (duration * 2);
	}

	var digits = creativeway.padNumber(String(creativeway.digits.current), 3).split('');

	creativeway.elements['numCourses'].find('div').each(function(i, o) {
		var div = $(o);
		var digit = div.attr('title');

		if (digit !== digits[i]) {
			creativeway.digits.animations.push(i);

			var pos = creativeway.digits.width * digits[i];
			div.attr('title', digits[i]);

			div.find('img').remove();
			div.
				append('<img src="/images/themes/business/numbers/top_'+digit+'.png" class="top">').
				append('<img src="/images/themes/business/numbers/bottom_'+digits[i]+'.png" class="bottom">');

			div.find('span:eq(0)').
				css({backgroundPosition:'-'+pos+'px 0'});

			div.find('img:eq(0)').
				animate({height:1, top:creativeway.digits.top.height, width:creativeway.digits.width}, duration, function() {
					$(this).remove();
				});

			div.find('img:eq(1)').
				delay(duration).
				animate({height:top.creativeway.digits.bottom.height, top:creativeway.digits.top.height, width:creativeway.digits.width}, duration, function() {
					div.find('span:eq(1)').css({backgroundPosition:'-'+pos+'px -'+top.creativeway.digits.top.height+'px'});
					$(this).remove();

					creativeway.digits.animations.pop();
					creativeway.animationCallback();
				});
		}
	});



	return true;
};

creativeway.animationCallback = function() {
	// check if all the digits have finished their animation and re-call the function
	if (!creativeway.digits.animations.length) {
		creativeway.animateTicker();
	}
};


creativeway.padNumber = function(n, len) {
   	s = n.toString();
    if (s.length < len) {
        s = ('0000000000' + s).slice(-len);
    }

    return s;
};


