$(function() {

	//var _jsonpath = "http://dev.plitto.com/json/";
	var _title = "";
	var _jsonpath = "http://www.plitto.com/json/";
	// Based off http://jqueryui.com/demos/autocomplete/#remote-jsonp
	
	// Search 7/21/2010
	$(function() {
		function log(message) {
			$("<div/>").text(message).prependTo("#log");
			$("#log").attr("scrollTop", 0);
		}
		
		$("#search").autocomplete({
			source: function(request, response) {
				$.ajax({
					url: "http://dev.plitto.com/json/search/" + request.term,
					//url: "http://www.plitto.com/json/search/" + request.term,
					dataType: "json",
					success: function(data) {
						//console.log(data.response);
						//console.log(data.results[0].name);
						response($.map(data.results, function(item) {
							return {
								label: item.name + '(' + item.count +')',
								value: item.name
							};
						}));
					}
				});
			},
			minLength: 1,
			select: function(event, ui) {
				// No need to do anything here.
					// log(ui.item ? ("Selected: " + ui.item.label + " Details: " + ui.item.value) : "Nothing selected, input was " + this.value);
					// Return the search results
					//$('#content').html("Search for " + ui.item.label + " Details: " + ui.item.value);
					// $('form').clearForm();
			},
			open: function() {
				$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
			},
			close: function() {
				$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
			}
		});
	});
	

/* JSON Template for Contacts 7/16/2010 */
function jtSearch(_title)
{
	return (
		'<div class="title"><div class="label">Search Results For: </div>' + _title + '</div>' + 
		'{.section results}{.repeated section @}' + 
		'<div class="{type} level3" id="{id}">{name} ({count})</div>' + 
		'{.end}{.end}');
}


// This procseses submitted forms
$.fn.formSubmit = function(type) {
	// console.log("type"); console.log(type);
	// console.log("Search: " + type);
	if(type == "search")
	{
		// console.log("Type: search");
		if(type.length===0)
		{
			$('#search').append("Search terms cannot be blank");
		}
	  // Inputs will be listID, Thing Name
	  var searchTerm = $('input#search').val();
	  var sendToJSON = _jsonpath + 'search/' + escape(searchTerm) +'/';
	  
	 // console.log("search term: " + searchTerm + " jp: " + sendToJSON);
	  
	  $.ajax({
		type: "POST",
		url: sendToJSON,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			// console.log("We made it to 29");
		  $('#content').html("Loading...");
			var t = jsontemplate.Template(jtSearch(msg.response));
			$('#content').html(t.expand(msg));
		}
	  });

	  // 	$('form').clearForm();
	// console.log("Thing, ListID: " + thingName + listID);
	}
	
	else if(type =="listAdd")
	{
	  // Inputs will be listID, Thing Name
	  var thingName = $('input#thingName').val();
	  var listID = $('input#listID').val();
	  
	  var sendToJSON = _jsonpath + 'listAdd/listID/' + listID + '/thingName/' + escape(thingName) +'/';
	  
	  $.ajax({
			type: "POST",
		url: sendToJSON,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			$('#homefeed').prepend(msg.response);
		}
	});

  	$('form').clearForm();
  }
  else if(type =="formAdd")
  {
	  // Inputs will be listID, Thing Name
	  var listName = $('input#listName').val();
	 //  $('#homefeed').prepend("Attempting to add " + listName + " with a length of "+ listName.length + "<br/>");
	  if(listName.length===0)
	  {
		  $('#homefeed').prepend("Empty items not allowed<br/>");
	  }
	  else
	  {
	  var lcJSON = _jsonpath + 'listCreate/' + escape(listName) +'/';
	  		//console.log("path"); console.log(lcJSON);
	  	// Take the JSON link to create an new list and run it.
	  	$.ajax({
	  		type: "POST",
	  		url: lcJSON,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
	  			// We should have an integer
	  				// console.log("int: " + isInt(msg.response));
	  			if(isInt(msg.response))
	  			{
	  				// we got our list ID back. Put it in the form, and do what we need to.
	  				
	  				// Set the new list as a variable, mainly for cleanliness.
	  				var listID = msg.response;
		  			// Build a new form
		  			var _form = addToList(listID);
	  				
	  				// Replace the old create list form
	  				$('#makeListForm').html('<div class="formLabel" style="float: left; display: inline;">Your list:</div>' +
	  					'<div class="linkL" id="'+ listID +'" style="font-size: 1.5em; margin-bottom: 5px;"> ' +listName+'</div>' +
	  					'<div class="formLabel">Step 2: Type in a thing to add (enter, repeat)</div>' + _form);
	  			}
	  			else
	  			{
	  				$('#homefeed').prepend("error: " + msg.response);
	  			}
			}
		});
	  }

  	$('form').clearForm();
	// console.log("Thing, ListID: " + thingName + listID);
  }
  else
  {
	  // console.log("Compare false.");
  }
	 
};  

function addToList(listID)
{
	return '<form name="listAdd" class="main" action="">' +    
	'<input type="text" name="thingName" id="thingName" size="30"/> '+
	'<input type="hidden" name="listID" value="'+ listID +'" id="listID"/> '+
	'<input type="submit" name="submit" class="button" value="Add" onclick="'+
		'$().formSubmit(\'listAdd\');' + 
		' return false;'+
	'"/>'+  
	'</form>';
}

function getData(_div,_tjp)
{
var jsSrc = _jsonpath + _tjp;
// 
console.log("div: " + _div + " json: "+ jsSrc + " \n");
$.ajax({
	type: "GET",
	url: jsSrc,
	contentType: "application/json; charset=utf-8",
	dataType: "json",
	success: function(msg) {
		// console.log("response");console.log(msg.response);
		if(msg.error)
		{
			$(_div).html("<div class='error'>error: " + msg.error + "</div>");
		}
		else
		{
			var _form = "";
			// Is this a list? If yes, create the form element.
			if(msg.headers[0].view == "list")
			{
				_form = addToList(msg.headers[0].listID);
			}
			
			/* Form to add list, then things to it. 7/19/2010 */ 
			else if (msg.response == "formAdd")
			{
				_form = '<div id="makeListForm"><form name="formAdd" class="main" action="">' +
				'<div class="formLabel">Step 1: Type in your List</div>' +
				'<input type="text" name="listName" id="listName" size="30"/> '+
		    	'<input type="submit" name="submit" class="button" value="Make List" onclick="'+
		    		'$().formSubmit(\'formAdd\');' + 
		    		' return false;'+
		    	'"/>'+  
		    	'</form></div>';
				$('#content').html('<div class="title">Make a List. Add to it.</div>' +
					_form + 	'<div id="results"></div>' +'<div id="homefeed"></div>');	
			}
			else
			{
				_form = "";
			}
			if (msg.headers[0].title)
				{	_title = msg.headers[0].title; } else { _title = ""; }

			// 	console.log("title: "+ msg.headers[0].title);console.log("schema: " + msg.schema);
			
			if(msg.schema =="user.menu.stats")
			{
				// Mustache
				var must_UserStats = '{{#data}}<div class="row"><div class="theKey">{{TheKey}}</div><div class="theValue">{{TheValue}}</div></div>{{/data}}';
				var str = '<div class="title">' + _title + '</div>' +Mustache.to_html(must_UserStats, msg).replace(/^\s*/mg, '');
				$(_div).html(str);
			}
			else if (msg.schema == "user.menu.things")
			{
				// console.log("things");
				var must_UserThings= '{{#data}}<div class="linkT tPage" id="{{ThingID}}">{{ThingName}}</div>{{/data}}';
				var str = '<div class="title">User\'s Things</div>' + Mustache.to_html(must_UserThings, msg).replace(/^\s*/mg, '');
				// $("#ui_viewMenu").html(str);
				$(_div).html(str);
			}
			else if(msg.schema =="user.menu.lists")
			{
				// console.log("227");
				var s = jsontemplate.Template(jtUserLists(_tjp,_title));
				$(_div).html(s.expand(msg));
			}
			else if(msg.schema == "feed")
			{
				// Change the whole view
				
				console.log(msg.headers[0].view);
				if(msg.headers[0].view=="person")
				{
					$("#ui_viewMenu").html("Person Stats");
				}
				else
				{
					$("#ui_viewMenu").html("No View");
				}
				var h = jsontemplate.Template(jtFeedHeaders(_tjp,_title,_form));
				var t = jsontemplate.Template(jtFeed(_tjp,_title, _form)); // Apply the template 
				$(_div).html( h.expand(msg) + t.expand(msg) );	// Shove it in the main content area
			}
			else if(msg.schema == "contactsInCommon")
			{
				var c = jsontemplate.Template(jtContacts(_tjp,_title, _form)); // Apply the template 
				$(_div).html(c.expand(msg) );	// Shove it in the main content area
			}
			else
			{
				// Do nothing.
				$(_div).html("<div class='title'>"+title+"</div>No Results because the data from the server was being too silly");
			}
		}
	}
});
}

/* JSON Template for User Lists 7/28/2010 */
function jtUserLists(_jspath, _title)
{
	return ('<div class="title">' + _title + '</div>{.section data}<div style="display:block; border-bottom: 2px #444 solid; font-weight: bold; ">List Name, Number In the List</div>{.repeated section @}' + 
				'<div class="linkL" id="{ParentListNameID}" style="border-bottom: 1px #444 solid; padding: 2px 0px 2px 0px;">{ListName} ({TheSize})'+
				// '<br/><div class="addedNote">Modified: {Modified} Created: {Created}</div>' +
				'</div>'+
		'{.end}{.end}');
}

/* JSON Template for Contacts 7/16/2010 */
function jtContacts(_jspath, _title)
{
	return ('<div class="title">' + _title + '</div>{.section data}<div id="homefeed" style="max-width: 450px;"><div style="border-bottom: 1px solid #999; background-color: #999;display: block;">'+
			'Person<div style="float: right; width: 100px;  ">InCommon</div></div>{.repeated section @}' +
			
			'<div class="linkP level3" id="{userID}" style="border-bottom: 1px solid #999; display: block; min-height: 50px;">'+
				'<div style="background-image:url(\'https:\/\/graph.facebook.com\/{fbuid}\/picture\'); height: 50px; width: 50px; float: left;"></div>' +
				'{userName}<div style="float: right; width: 100px; font-size: 1.4em; text-align: right;">{inCommon}</div>' +
			'</div>' +
		'{.end}</div>{.end}');
}

function jtFeedHeaders(_jspath,_title, _form)
{
	return ('{.section headers}{.repeated section @}' +
	
	// Build the filter buttons, if there is no child.
	'{.section child}' + 
	'Filtered by: {filter}' +
	'{.or}' +
	'<div class="title" id="viewtitle"><div class="label">{view}: </div>' + _title + '</div>' + // Start with the page title
		// List add, if it is there.
		_form + 
		'{.section menu}<ul class="buttons"><li style="border: 0px; color: #000;" id="filter/Text">Their:</li> 	' +
		'<li class="feedMenu all" id="' + _jspath + 'filter/all/child/"></li>' +
		'{.repeated section @}' +
		'<li class="feedMenu {button}" id="' + _jspath + 'menu/{button}/">{button}</li>' +
		'{.end}</ul><div id="withMenu">{.end}' +
		
		'{.section buttons}<ul class="buttons"><li style="border: 0px; color: #000;" id="filter/Text">Filter:</li> {.repeated section @}' +
			'<li class="feedFilter {button}" id="' + _jspath + 'filter/{button}/child/"></li>' +
		'{.end}</ul>{.end}' +

	'{.end}' + 
	'{.end}{.end}');
		
}

/* JSON Template for the Feed, List, Person 7/2010 */
function jtFeed(_jspath){ 
	return(

		'{.section data}<div id="homefeed"><div class="viewLabel">Their Feed</div>' + 
			'{.repeated section @}' +
			// Things will come in the correct order. This ordering is irrelevant.
			'{.section person}{.repeated section @}<div class="level{level} linkP" id="{UserID}">' +
			'<div class="userIcon" style="background-image:url(\'https:\/\/graph.facebook.com\/{fbuid}\/picture\');"></div>{UserName}</div>{.end}{.end}' +
			'{.section list}{.repeated section @}<div class="level{level} linkL" id="{ListID}">{ListName}</div>{.end}{.end}' +
			'{.section thing}{.repeated section @}<div class="level{level}">'+
				
				'<div class="{inco} inc" id="'+ _jsonpath +'ditto/lu/{UserID}/li/{ListID}/lt/{ThingID}/"></div>'+
				'<div class="addedNote">{Added} days ago</div>'+
				'<div class="linkT"  id="{ThingID}">{ThingName}</div>'+
				
			'</div>{.end}{.end}' +

		'{.end}'+
			

		
		'{.end}' + 
		
		// Page Next - Inside the Homefeed
		'{.section pageNext}<div class="pages">{.repeated section @}' +
			' <div id="{path}/child" class="{label} page">{text}</div>' + 
		'{.end}' + 
		'</div>{.end}'+
		'{.section menu}</div>{.end}' + 
		
		'</div>'
		);
}

/* Links to People, Lists, Things 7/2010 */
	$("div.linkP").live("click",function(){ $("#content").html("Loading..."); 
		var linkPJSON = "person/" + $(this).attr('id')+"/"; getData("#content",linkPJSON); 
		location.hash = "#/user/" + $(this).attr('id'); 
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
	});
	$("div.linkL").live("click",function(){ $("#content").html("Loading...");  
		var linkLJSON = "list/" + $(this).attr('id')+"/";	getData("#content",linkLJSON);
		location.hash = "#/list/" + $(this).attr('id');
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
	});
	$("div.linkT").live("click",function(){ $("#content").html("Loading..."); 
		var linkTJSON = "thing/" + $(this).attr('id')+"/";	getData("#content",linkTJSON);
		location.hash = "#/thing/" + $(this).attr('id');
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
	});

/* Page Ahead/Back  7/29/2010 */
$("div.page").live("click", function() {
	var thisID = $(this).attr('id');
	// console.log(thisID);
	$("#homefeed").html("Loading...");
	// This is the parameter that gets sent to get the JSON
	getData("#homefeed", thisID + "/");
});
	
/* Main navigation between elements using only JSON 6/2010 */
	// Handle the main buttons
	$("a.navItem").live("click", function() {
		var thisID = $(this).attr('id');
		$("#content").html("Loading...");
		// This is the parameter that gets sent to get the JSON
		getData("#content", thisID + "/");
		
		// Reset the active tabs
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
		// $("a.navItem:not('#"+ thisID + "')").addClass("highlighted");
		//the above accomplishes same as the two lines together, you can get rid of this:
		$("#" + thisID ).removeClass("notHighlighted").addClass("highlighted");
	});

// Filters 7/16/2010
$("li.feedFilter").live("click", function() {
	// The id includes the entire required JSON
	$("#homefeed").html("Loading...");
	var ffJPath = $(this).attr("id");
	var ffCleaned = ffJPath.replace(/\//g,"\\/"); // escape(ffJPath) doesn't work.
	// console.log(ffCleaned);
	$("#" + ffCleaned).addClass("highlighted");
	
	// Clear, then re-add the highlighting for the filter.
	$("li.feedFilter").removeClass("highlighted");
	$("#" + ffCleaned).addClass("highlighted");
	
	getData("#homefeed",ffJPath);
});

//Menus 7/26/2010
$("li.feedMenu").live("click", function() {
	// The id includes the entire required JSON
	$("#withMenu").html("Loading...");
	var ffJPath = $(this).attr("id");
	var ffCleaned = ffJPath.replace(/\//g,"\\/"); // escape(ffJPath) doesn't work.
	// console.log(ffCleaned);
	$("#" + ffCleaned).addClass("highlighted");
	
	// Clear, then re-add the highlighting for the filter.
	$("li.feedMenu").removeClass("highlighted");
	$("#" + ffCleaned).addClass("highlighted");
	
	getData("#withMenu",ffJPath);
});

/* Ditto/Remove status 7/15/2010 */
	/* Handle the ditto click action */
	$("div.inc").live("click", function() {
	var _inc = "";
	if ($(this).hasClass("icYes")) {
		$(this).toggle().removeClass("icYes").addClass("icNo").fadeIn(300);
		_inc = "lc/icYes/";
	} else {
		$(this).toggle().removeClass("icNo").addClass("icYes").fadeIn(300);
		_inc = "lc/icNo/";
	}
	// The JSON path is the id of the icon div.
	var incJSONPath = $(this).attr("id");
		$.ajax({
			type: "POST",
			url: incJSONPath + _inc,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
				// console.log("We made it to 143 Notice: " + msg.notice);
				$('#action').prepend("notice: " + msg.notice + " \n path: " + incJSONPath + "\n");
			}
		});

	});
	
	/* Handle the removing of an item. Not Functional 7.19.2010 */
	$("div.dittoRemove").click(function() {
		// Get the current ID
		var$this =$(this);
		var str = "#"+$(this).attr("id").replace("remove", "");
		$(str).addClass("iconDitto").removeClass("iconInCommon").removeClass("showNo").addClass("showYes");
		$(str+ "extras").addClass("showNo").removeClass("showYes");
		$(str+ "alertRemoved").toggle().pause(500).fadeOut(700);
		// Switch the icon from checked to unchecked.
		//$("#"+$(this).attr("id")+"extras").removeClass("showNo").addClass("showYes");
	});
	
	// This is from the learn JQuery blog. 7/17/2010
	$.fn.clearForm = function() {
		return this.each(function() {
			var type = this.type, tag = this.tagName.toLowerCase();
			if (tag == 'form') {return $(':input',this).clearForm();}
			if (type == 'text' || type == 'password' || tag == 'textarea') {this.value = ''; }
			else if (type == 'checkbox' || type == 'radio') { this.checked = false; }
			else if (tag == 'select') { this.selectedIndex = -1; }
		});
	};
	
	/* control the pause * Convert this to something like return setTimeout(duration, function(){return this}) 5/2010 */
	$.fn.pause = function(duration) {
		$(this).animate({ dummy: 1 }, duration);
		return this;
	};

	
	function isInt(s) {
		  return (s.toString().search(/^-?[0-9]+$/) === 0);
		}
	
	var _hash = location.hash.split("/",6); 
	// console.log("hash" + _hash);
	
	/* Control the navigation based on the hash tags 8/1/2010 */
	if(_hash[1] in {'home':'','contacts':'','add':'','about':'','/home':''})
	{	
		// console.log("div#" + _hash[1]);
		getData("#content",_hash[1] + "/"); 
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
		$("div#" + _hash[1]).removeClass("notHighlighted").addClass("highlighted");
		location.hash = '#/' + _hash[1];
		
	}
	else if (_hash[1]== "user")
	{ 
		// Uncheck buttons
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
		$("#content").html("Loading..."); 
		getData("#content","person/" + _hash[2] +"/");
	}
	else if (_hash[1]== "thing")
	{ 
		// Uncheck buttons
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
		$("#content").html("Loading..."); 
		getData("#content","thing/" + _hash[2] +"/");
	}
	else if (_hash[1]== "list")
	{ 
		// Uncheck buttons
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
		$("#content").html("Loading..."); 
		getData("#content","list/" + _hash[2] +"/");
	}
	else
	{
		getData("#content","home/"); 
		$("a.navItem").removeClass("highlighted").addClass("notHighlighted");
		$("div#home").removeClass("notHighlighted").addClass("highlighted");
		location.hash = '#/home';
	}

});