(function($) {
  $.fn.ContentSlider = function(options)
  {
    var defaults = {
      width : '400px',
      height : '400px',
      speed : 400,
      easing : 'easeOutQuad',
      textResize : false,
      IE_h2 : '26px',
      IE_p : '11px'
    }
    var defaultWidth = defaults.width;
    var o = $.extend(defaults, options);
    var w = parseInt(o.width);
    var n = this.children('.cs_wrapper').children('.cs_slider').children('.cs_page').length;
    var x = -1*w*n+w; // Minimum left value
    var p = parseInt(o.width)/parseInt(defaultWidth);
    var thisInstance = this.attr('id');
    var inuse = false; // Prevents colliding animations

    function moveSlider(d, b)
    {
      var l = parseInt($('.cs_wrapper').children('.cs_slider').css('left'));

      if(isNaN(l)) {
        var l = 0;
      }

      var m = (d=='left') ? l-w : l+w;
	  
	  var jj = m - x;
	  var jjp = -jj / x;
	  var percent = 1 - jjp;
	  var percent = percent * 100;
	  var percent = Math.round(percent);
	
	  //progress bar
	  $("#progressbar").progressbar( "option", "value", percent );
	  $("#progresspercent").html(percent+'%');
      if(m <= 0 && m >= x) {
        $('.cs_wrapper')
            .children('.cs_slider')
              .animate({ 'left':m+'px' }, o.speed, o.easing, function() {
                inuse=false;
              });
      }
    }

    return this.each(function() {
      $(this)
        // Set the width and height of the div to the defined size
        .css({
          width:o.width,
          height:o.height
        })
        // Dig down to the page div elements
        .find('.cs_page')
          // Set the width and height of the div to the defined size
          .css({
            width:o.width,
            height:o.height
          })
          .end();

		var nextBtn = $('.nextPage');
		nextBtn.bind('click', function() {
			var q = $(this).attr('id');
			if (undefined === $("input[name='"+q+"']:checked").val()) {
				alert('Please choose an answer before moving on to the next question.');
				return false;
			} else {
				// get checked val, ajax post, move on
				var val = $("input[name='"+q+"']:checked").map(function(i,n) {
				        return $(n).val();
				    }).get();
				$.post ("/answer", { question: q, "answer[]": val }, function(data) { moveSlider('left', nextBtn); });
				return false;
			}
		});
		var prevBtn = $('.prevPage');
		prevBtn.bind('click', function() {
			moveSlider('right', prevBtn);
		});
    });
  }
})(jQuery)
