var step = 3;

var images;
var round = 1;
var added_images = 0;
var scored_images = 0;

// Main driver function
$(document).ready(function(){
	// Set up the carousel
	$('#mycarousel').jcarousel({
		easing: 'easeInOutBack',
        animation: 650,
		initCallback: mycarousel_initCallback
    });
});

// Custom animation for carousel
jQuery.easing['easeInOutBack'] = function (x, t, b, c, d, s) {
  if (s == undefined) s = 1.70158; 
  if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
  return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}

// Called when carousel is initialized
function mycarousel_initCallback(carousel, state) {
  // All scoring buttons should send a score and move the carousel
  $("#love, #like, #ok, #dont, #hate, #skip").click(function() {
    // Score the current image
    image_id = $('#quiz_loader img').attr('alt');
    style_id = this.id;
    scoreImage(carousel, image_id, style_id);

    // Show the spinner again
    $('#quiz_loader').addClass('loading').html('&nbsp;');
  });

  // The non-neutral score buttons should indicate that a style has been
  // included or ruled out in the "progress" grid
	$("#love, #like, #dont, #hate").click(function(){
		var avail = $(".progress div").not(".eliminated, .favorite");
    var new_class;
    var selected = $(this).attr("id");
    if(selected == "love" || selected == "like") {
        new_class = "favorite";
    } else {
        new_class = "eliminated";
        $("#ruledOut").html(parseInt($("#ruledOut").html()) + 1);
        $("#potential").html(parseInt($("#potential").html()) - 1);
    }    
		$(avail[Math.round(Math.random() * avail.length)]).addClass(new_class);
	});

  // Get the first set of images
  $.ajax({
    type: 'GET',
    url: '/StyleEngine',
    data: 'next_round=' + true,
    dataType: 'json',
    success: function(data) {
      images = data;
      mycarousel_addImages(carousel);
      nextStep(carousel);
    },
    error: function(data, error) {
      alert('There was an error loading the StyleEngine, please try again later.');
    }
  });
}

function mycarousel_addPadding(carousel, num, offset) {
  for (i = offset; i < offset + num; i++) {
    var blank_img = '<img width="150" height="137" src="/images/pixel-1x1-white.gif" alt=""/>';
    carousel.add(i, blank_img);
  }
  carousel.size(carousel.size() + 2);
}

function mycarousel_addImages(carousel) {
	
    // Clear the number of images that have been added
    added_images = 0;
	offset = 0;
	
	if($.browser.msie && $.browser.version == '6.0'){
	//if(false){
		$("#mycarousel").css("display", "none");
	}
	
	// Pad with two images at the beginning
	mycarousel_addPadding(carousel, 2, 0);
	offset = 2;
	
    // Add the entire array of image thumbnails
    for (i in images) {
        carousel.add(offset, images[i]['small']);
        offset++;
        added_images++;
    }
	
	
    // Pad with two images at the end
    mycarousel_addPadding(carousel, 2, offset);
    offset += 2;
	
    // Set the new carousel size
    carousel.size(offset);

    $('#mycarousel img').each(function(i) {
        $(this).attr('width', 150);
        $(this).attr('id', 'img' + (i+1));
    });

    // Fade all but the first one
    $("#mycarousel img:not(#img3)").fadeTo(551, .5);
    
    // Add loading to the last 2 images (this will be removed later)
    $($("#mycarousel img").get().splice(18, 1)).parent().addClass("loading");
}

// Sends an image score to the server
function scoreImage(carousel, item_id, score) {
    /*
    var html = $('#score_log').html();
    html += "step(" + step + ") score(" + score + ") item_id(" + item_id + ")<br/>\n";
    $('#score_log').html(html);
    */
    $.post(
        '/StyleEngine', 
        {
            item_id: item_id,
            score: score,
            ratings: $("#ratingsData").serialize()
        }
    );
    scored_images++;

    // Are we at the end of the quiz?
    if (scored_images == added_images) {
        // If we're at the end of the first round, get a new
        // set of images to show and display them, otherwise
        // end the quiz and show the scores
        if (round == 1) {
            round = 2;
            
            $.get(
                '/StyleEngine',
                {
                    next_round: true
                },
                function(data) {
                    images = images.concat(data);
                    mycarousel_addImages(carousel);
                    
                    //remove loading on the last 2 images
           		 	$("#mycarousel li").removeClass("loading");
           		 	
                    nextStep(carousel);
                },
                'json'
            );
        } else {
            endQuiz();
        }
    } else {
        nextStep(carousel);
    }
}

function endQuiz() {
  $("#love, #like, #ok, #dont, #hate, #skip").unbind('click');
  $("#attribution").remove(); //remove old source link
  $.get(
    '/StyleEngine',
    {
      end_quiz: true
    },
    function(results) {
      $("#mycarousel #img" + (step - 1)).fadeTo(5, .5);
      $("#quiz_completed").html(results);
      $("#quiz_loader").toggle();
      $("#quiz_completed").toggle();
    }
  );
}


function getImageURL(thumb_url) {
  return thumb_url.replace(/engineimages_small/, 'engineimages');
}


function nextStep(carousel) {
	/*if(!$("#mycarousel #img" + step) || !$("#mycarousel #img" + step).attr('src')){
		step++;
		nextStep(carousel);
	}*/
	//alert(step);
    thumb_url = $("#mycarousel #img" + step).attr('src');
    thumb_id  = $("#mycarousel #img" + step).attr('alt');

	  doAttribution();
	
    var img = new Image();

    // once the image has loaded, execute this code
    //alert('loading');
    $(img).load(function () {
        // set the image hidden by default    
        $(this).hide();
        
        // with the holding div #loader, apply:
        $('#quiz_loader')
            // remove the loading class (so no background spinner), 
            .removeClass('loading')
            // then insert our image
            .html(this);
        
        // fade our image in to create a nice effect
        $(this).fadeIn();
        //alert('loaded');

    // if there was an error loading the image, react accordingly
    // notify the user that the image could not be loaded
    }).error(function () {
      
    // *finally*, set the src attribute of the new image to our image
    }).attr('src', getImageURL(thumb_url))
      .attr('alt', thumb_id);
        
	step++;

    // Scroll to the next image
    carousel.scroll(step - 3);

    // Fade out the old thumbnail, fade in the new one
    $("#mycarousel #img" + (step - 2)).fadeTo(5, .5);
    $("#mycarousel #img" + (step - 1)).fadeTo(5, 1);
}


function doAttribution(){
	
	var defRatings = ["Sofa",
					"Lounge Chair / Ottoman",
					"Coffee Table",
					"Side Table",
					"Rug / Carpet",
					"Floor Lamp",
					"Table Lamp",
					"Throw Pillows",
					"Media Cabinet",
					"Book Case or Storage Cabinet",
					"Art / Accessories",
					"Window Treatments",
					"Colors"];
					
	// IE6 can fuckoff. seriously.
	if(!images[step-3]){
		return;
	}
	if(images[step-3].attr){
		// setup the source url
		
		
		
		$("#attribution").html('<a href="'+ images[step-3].attr.url +'" target="_blank">source</a>');
		
		//clean up old li's
		$("#ratings ul li").remove();
		
		// list all the items for that image.
		if(images[step-3].attr.items){
			$(images[step-3].attr.items).each(function(i){
				$("#ratings ul").append("<li><div class='lhspace'>"+ images[step-3].attr.items[i] +"</div><input type='radio' id='rl"+i+"' name='rating-"+defRatings[i]+"' value='1'> <label for='rl"+i+"'>Like</label> <input type='radio' id='rh"+i+"' name='rating-"+defRatings[i]+"' value='0'> <label for='rh"+i+"'>Hate</label></li>");
			});
		}else{
			$(defRatings).each(function(i){
				$("#ratings ul").append("<li><div class='lhspace'>"+ defRatings[i] +"</div><input type='radio' id='rl"+i+"' name='rating-"+defRatings[i]+"' value='1'> <label for='rl"+i+"'>Like</label> <input type='radio' id='rh"+i+"' name='rating-"+defRatings[i]+"' value='0'> <label for='rh"+i+"'>Hate</label></li>");
			});
		}
		
	}else{
		// no attribution, also setup default items
		$("#attribution").html('');
		$("#ratings ul li").remove();
		$(defRatings).each(function(i){
			$("#ratings ul").append("<li><div class='lhspace'>"+ defRatings[i] +"</div><input type='radio' id='rl"+i+"' name='rating-"+defRatings[i]+"' value='1'> <label for='rl"+i+"'>Like</label> <input type='radio' id='rh"+i+"' name='rating-"+defRatings[i]+"' value='0'> <label for='rh"+i+"'>Hate</label></li>");
		});
	}
	
	//make the radios have 3 states.
	$("#ratings :radio").behaveLikeCheckbox();
	
}

/*
* Handle the image ratings.
* @author David Jeffries
*/
function toggleRatings(){
	$("#possibleMatches, #ratings, #instructions").toggle();
}
jQuery.fn.extend({
  behaveLikeCheckbox: function(){
  	var radioStatus	=	false;
  	$.each($(this),function(){
  		$(this).data("status",$(this).attr("checked"));
  		$(this).mouseover(function(){
  			this.radioStatus = $(this).attr("checked");
  			$(this).data("status",$(this).attr("checked"));
  		});
  		$(this).click(function(){
  			if($(this).data("status") != true)
  			{
  				$(this).attr("checked",true);
  				$(this).data("status",true);
  			}
  			else	
  			{
  				$(this).attr("checked",false);
  				$(this).data("status",false);
  			}
  		});
  	});
  	return this;
  }
});

