function saveBowl()
{
  var items = $("#current-bowl-contents li");
  var itemStringsArray = new Array;
  
  for(var index = 0; index < items.length; index++)
  {
    var item = $(items[index]).text();
    itemStringsArray.push(item);
  }
  
  var encoded = $.json.serialize(itemStringsArray);

  jQuery.cookie('bowlOrder', encoded, { path: '/', expires: 365 });
}

function loadBowl()
{
  $("#current-bowl-contents").empty();
  
  if (jQuery.cookie('bowlOrder'))
  {
    var bowlItems = $.json.deserialize(jQuery.cookie('bowlOrder'));
    
    var length = bowlItems.length;
    
    for(var index = 0; index < bowlItems.length; index++)
    {
      insertInList(bowlItems[index]);
    }
  }
}

function insertInList(value)
{
  var characterHTML = '<li><a href="#" id="person01" class="delete"></a><h4>' + value + '</h4></li>';
  
  $("#current-bowl-contents").append(characterHTML);
  
}

function clearForm()
{
  $('select#character-type').val("adult-female");
  var name = $('input#name').val("");
  var age = $('input#age').val("");
}

function clearShoppingCart()
{
  if (confirm("Are you sure you want to clear this bowl?"))
  {
	  $("#current-bowl-contents").empty();

	  saveBowl();

		updateNotification();
  }
}

function addToBowl(type, name, age)
{
  var characterHTML = name;
  if (age != "") {characterHTML += ' - ' + age + ' yrs'};
  characterHTML += ' (' + type + ')';
  
  // insert into HTML
  insertInList(characterHTML);
  
  // save bowl list to cookie
  saveBowl();
  
  // clear the form
  clearForm();

	updateNotification();
}

function updateNotification()
{
	var items = $("#current-bowl-contents li");
  if ((items.length < 12) || (items.length > 24))
  {
		$("#notification").show();
	}
	else
	{
		$("#notification").hide();
	}
}

function updateBowlOrder(event, ui)
{
  // resave the bowl contents in the current order
  saveBowl();
}

function validateBowlContents()
{
  // make sure we're in the right range of number of people on bowl
  var items = $("#current-bowl-contents li");
  if (items.length < 1)
  {
    alert("You have not added any characters to your bowl.");
    return false;
  }
  if (items.length < 12)
  {
    return confirm("Its best to have at least 12 characters on a bowl so that hands connect. After you place your order, Betty will work with you to create a nice alternative. Would you like to proceed?");
  }
  if (items.length > 24)
  {
    alert("You cannot have more than 24 people on a bowl. They just won't fit. Sorry.");
    return false;
  }
  
  return true;
}

String.prototype.atify = function() { 
	return this.replace(/@[\w]+/g, function(m) { 
			return "<a href='http://www.twitter.com/"+m.replace('@','')+"' target='_blank'>"+m+"</a>"; 
		}); 
};

String.prototype.linkify = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
		  return "<a href='"+m+"' target='_blank' onClick=\"javascript: pageTracker._trackPageview('/outgoing/"+m.replace('http://', '')+"');\">"+m+"</a>"; 
    	return m.link(m);
  	});
}; 





$(document).ready(function () {
	$("#notification").hide();
  
/*	
	if ((location.pathname == "/") || (location.pathname == "/index.php"))
	{
	  $("#header").fadeIn("slow");
	  $("#content").fadeIn("slow");
	  $("#footer").fadeIn("slow");
	}
	else
	{
	  $("#header").show();
	  $("#content").show();
	  $("#footer").show();
	}
*/
  loadBowl();

  Shadowbox.init({players: ["img", "swf", "qt"],
                  displayNav: "true",
                  flashVersion: "8.0.0"});
  
//  $("#gallery a").lightBox();

  
  // make current bowl list sortable
	$("#current-bowl-contents").sortable({
     update: updateBowlOrder
  });
	$("#current-bowl-contents").disableSelection();
	
	// register for ADD person submission
	$("#form-add").click(function() {
	  var character_type = $('select#character-type option:selected').val();
	  var name = $('input#name').val();
	  var age = $('input#age').val();
	  
	  if (!character_type || (name == ""))
	  {
	    alert("character type and name are required");
		  return false;
	  }

    // add the character to the character list
    addToBowl(character_type, name, age);
    
	  return false;
	  
	});

	// register for DONE submission
	$("#form-done").click(function() {
	  
	  if (validateBowlContents())
	  {
      window.location = "/checkout.php";
	  }
    
	  return false;
	  
	});

	// register for CLEAR
	$("#form-clear").click(function() {
	  clearShoppingCart();
    
	  return false;
	});


	// register for EDIT submission
	$("#form-edit").click(function() {
    window.location = "/build.php";
    
	  return false;
	  
	});

		
	$(".delete").live("click", function() {
	  if (confirm("Are you sure you want to remove this person?"))
	  {
	    $(this).parent().remove();
	  }

	  saveBowl();

		updateNotification();
	  
	  return false;
	});

  // register for cart submission
	$("#shopping_cart").submit( function() {
	  if (validateBowlContents())
	  {
			// add each character to the shopping cart
		  if (jQuery.cookie('bowlOrder'))
		  {
		    var bowlItems = $.json.deserialize(jQuery.cookie('bowlOrder'));

		    var length = bowlItems.length;

		    for(var index = 0; index < bowlItems.length; index++)
		    {
  				var itemHTML = '<input type="hidden" name="item_name_' + (index+2) + '" value="' +  bowlItems[index] + '" >';
  				var amountHTML = '<input type="hidden" name="amount_' + (index+2) + '" value="0" >';
		      var quantityHTML = '<input type="hidden" name="quantity_' + (index+2) + '" value="1">';
				  $("#shopping_cart").append(itemHTML);
				  $("#shopping_cart").append(amountHTML);
				  $("#shopping_cart").append(quantityHTML);
		    }
		
				// now add special notes as an item (need to devide into 127 character chunks)
				var nextID = length + 2;
				var specialNotes = $("#shopping_cart textarea").val();
				var numChunks = Math.floor(specialNotes.length / 127) + 1;
				
				for (var chunkID = 0; chunkID < numChunks; chunkID++)
				{
					var thisChunk = specialNotes.substr((chunkID * 127), 127 );
					var specialNotesItemHTML = '<input type="hidden" name="item_name_' + (chunkID + nextID) + '" value="' + thisChunk + '"';
					var specialNotesAmountHTML = '<input type="hidden" name="amount_' + (chunkID + nextID) + '" value="0" >';
		      var specialNotesQuantityHTML = '<input type="hidden" name="quantity_' + (chunkID + nextID) + '" value="1">';
				  $("#shopping_cart").append(specialNotesItemHTML);
				  $("#shopping_cart").append(specialNotesAmountHTML);
				  $("#shopping_cart").append(specialNotesQuantityHTML);
				}
		  }

	    return true;
	  }

	  return false;
	});

	
	var items = $("#current-bowl-contents li");
  if ((items.length < 12) || (items.length > 24))
  {
    $("#notification").show();
  }

});