$(document).ready(function() {
	if ($("#landing_page").length != 0) preloadFridgeImages();
	$("#tell_me").click( function(e) {
		if (!validResult("#numbers"))
		{
			e.preventDefault();
			errorMessage("#drag_field");
		}
		else
		{
			var results = getResultsFromList("#numbers");
			var query = turnArrayToQueryString(results);
			$("#hidden input").attr("value", query);
		}
	});
	
	$("#colors li img").mouseover(function() {
	        var $big = $("#fridge_feature img") // the big fridge on the left
	        var bigsrc = $big.attr("src");
	        var pattern = /fridge\d{1,2}/; // this regex matches fridge0, fridge5, fridge10 etc
	        var oldfridge = pattern.exec(bigsrc)[0]; // returns fridgeX as a string
	        var newfridge = $(this).attr("id"); // which fridge is currently mouse-overed
	        var newsrc = bigsrc.replace(oldfridge, newfridge);
	        $big.attr("src", newsrc); // now the src is changed to reflect the mouse-overed thumbnail
	        var $featureNote = $("#fridge_feature p"); // we also need to change the innerHTML of the note under the big fridge
	        $featureNote.html($(this).attr("alt")); // the alt text contains the name of the fridge
	        $featureNote.addClass("fridge_title"); // add a class, so the titles can be styled differently than the original contents
	});
	
	var dragField = $("#drag_field");
	$("#numbers li").each( function() {
	    $(this).data("already_full", false);
	});
	$("#numbers li div.bucket").droppable({
	    tolerance: 'touch',
		accept: "#colors li img",
		drop: function(ev, ui) {
			var bucket = $(this).parent("li");
		    var fridge = ui.draggable;
		    
		    if (ui.position.top < 131) {
	            fridge.css("top", 133);
	         }
		     if (bucket.data("already_full") == false)
		     {
                var fridgeId = fridge.attr("id") + "_dropped"; 
			    bucket.attr("id", fridgeId);
	            fridge.data("parent_id", bucket.attr("id"));
	            bucket.data("already_full", true); 
		     }
		},
		out: function(ev, ui) {
		    var fridge = ui.draggable;
            var bucket = $(this).parent("li");
		    if (fridge.data("parent_id") == bucket.attr("id"))
            {
                bucket.removeAttr("id");
                bucket.data("already_full", false);
            }
		}
	});
	
	$("#colors li").droppable( { accept: "#colors li img", snap: "#colors li" });
	
	$("#colors li img").draggable({
		containment: dragField, 
		snap: "#numbers li div.snapper",
		snapTolerance: 10,
		stack: {group: '#colors li img', min: 4},
        revert: "invalid"
	});
	
	$("#reset").click( function(e) {
		e.preventDefault();
		$("#colors li img").each( function() {
		   $(this).css({ 
		        position: 'static',
		        top: '0px',
		        left: '0px'
		   });
		   $(this).css('position', 'relative');
		   $(this).data("parent_id", null);
		});
		$("p.error").remove();
		$("#numbers li").each( function() {
		    $(this).removeAttr("id");
		    $(this).data("already_full", false);
		});
	});
});

preloadFridgeImages = function() {
   images = [];
   for (i = 1; i < 11; i++)
   {
        images[i] = new Image();
        images[i].src = root + "_res/i/fridge" + i + "_big.jpg";
   }
}

validResult = function(list) {
	var $list_items = $(list).children("li");
	var validId = /^fridge\d{1,2}_dropped$/
	var allValid = true;
	$list_items.each( function() {
		isValid = validId.test($(this).attr("id"));
		if (!isValid) allValid = false;
	});
	return allValid;
}

hasDuplicates = function(list) {
	var $list_items = $(list).children("li");
	var numberTotal = 0;
	$list_items.each( function() {
		var num = $(this).attr("id").replace("fridge", "").replace("_dropped", "");
		numberTotal = parseInt(numberTotal) + parseInt(num);
	});
	if (numberTotal != 55)
	{
	    return true;
	} 
    else
    {
        return false;
    } 
}

getResultsFromList = function(list) {
	var $list_items = $(list).children("li");
	var results = [];
	$list_items.each( function() {
		var id = $(this).attr("id").replace("fridge", "").replace("_dropped", "");
		results.push(id);
	})
	return results;
}

turnArrayToQueryString = function(array) {
	var query = "";
	for (i = 0; i < array.length; i++) {
		array[i] = array[i].replace("fridge", "");
		query += array[i];
		if (i < (array.length -1)) {
			query += ",";
		}
	}
	return query;
}

errorMessage = function(container) {
	$container = $(container);
	$container.children("p.error").remove();
	var errorMsg = $container.prepend("<p class='error'>Your submission was not successful. Please check that all ten placements are filled and try again.</p>");
}

if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}