

$(function(){
    //     var _jsonpath = "http://dev.plitto.com/json/";
    // 
    var _jsonpath = "http://www.plitto.com/json/";
    var _title = "";
    


// Search
$("input#search").keyup(
      function(){
         //console.log(search.value);
         if(search.value.length>1)
         {
            $("#content").html('<div class="title">Search Results for <b>'+search.value+'</b></div><br/>');
            $.getJSON(_jsonpath+"search/"+search.value, function(data) {  
               //console.log(data);
            var thelist = '';   
               //process response
                        
               if(data.results)
               {
                  
                  $.each(data.results, function(i, val){  
                     console.log(data.results[i].theType);
                    if(data.results[i].theType=="List")
                    {
                       thelist += '<div class="level2 linkL" id="'+data.results[i].id+'">List: '+ data.results[i].name + ' ('+data.results[i].count+')</div>';
                    }
                    else if(data.results[i].theType=="Thing")
                    {
                       thelist += '<div class="level3 linkT" id="'+data.results[i].id+'">Thing: '+ data.results[i].name + ' ('+data.results[i].count+')</div>';
                    }
                    
                  });  
               
                  $('#content').append(thelist);
               }
               else
               {
                  console.log("no results");
                  $("#content").append("<i>No Results</i>"); 
                
               }
               
             });  
         }
      });    

    
    // Based off http://jqueryui.com/demos/autocomplete/#remote-jsonp
 
        // console.log("829 - plitto.js");  
        getData("#dashboard","dash/");  
    
    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };

    function getPosition(arrayName,arrayItem)
    {
        for(var i=0;i<arrayName.length;i++){
           if(arrayName[i]==arrayItem)
                return i;
        }
    }

    function filters( tjp , obj)
    {
      // Remove the previous filter from tjp
      // console.log(tjp); 

      var tjpArr = tjp.split('/');
        // console.log(tjpArr);        // console.log(tjpArr.length);

      if(getPosition(tjpArr,"filter"))
      {
        // Remove from that spot to the end.
          // console.log("position: " + getPosition(tjpArr,"filter") + " size: " + tjpArr.length);
         //console.log("Found filter");
         tjpArr.remove(getPosition(tjpArr,"filter"),tjpArr.length);
      }
        // console.log(tjpArr);
      
      // Put the string back together
      var newtjp = tjpArr.join("/");
      // console.log(newtjp);

      var _str = '<ul class="buttons"><li style="border: 0px; color: #000;" id="filter/Text">Filter: </li>';
      for (a in obj)
      {
        if(obj[a].button)
        {
        _str += '<li class="feedFilter ' + obj[a].button + '" id="' + newtjp + '/filter/' + obj[a].button + '/child/"/>';
        }
      }
      _str += '</ul>';
      
      return _str;
    }

$.fn.formSearch = function(search){
           
            // console.log("Type: search");
            //console.log("search for: "+search);
            //console.log('input#searchtext')
            if (search.length === 0)
            {
                $('#search').append("Search terms cannot be blank");
            }
            // Inputs will be listID, Thing Name
            //var searchTerm = $(search).val();
            var sendToJSON = _jsonpath + 'search/' + escape(search) + '/';

            // console.log("search term: " + search + " 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("<span class='title'>Search for <b>" + search + "</b></span><br/>");
                    var results ='';
                    for (i in msg.results)
                    {
                       if(msg.results[i].theType=="List")
                       {
                           results += "<div class='linkL' id='"+msg.results[i].id+"'>List: <b>"+msg.results[i].name + "</b> ("+msg.results[i].count+")</div><br/>";      
                       }
                       else if(msg.results[i].theType=="Thing")
                       {
                           results += "<div class='linkT' id='"+ msg.results[i].id+"'>Thing: <b>"+msg.results[i].name + "</b> ("+msg.results[i].count+")</div><br/>";      
                       }
                     
                    }
                    
                    if(i==0)
                    results += "<i>No results</i>";
                    
                    $('#content').append(results);
                    
                    //var t = jsontemplate.Template(jtSearch(msg.response));
                    //$('#content').html(t.expand(msg));
                }
            });
}

    // This procseses submitted forms
    $.fn.formSubmit = function(type){
        // console.log("type"); console.log(type);
        // console.log("Search: " + type);

        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")
        {
          // console.log("Add a form!");
            // 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);
                // console.log(msg);

                if (msg.error)
                {
                    $(_div).html("<div class='error'>error: " + msg.error + "</div>");
                }
                // Begin the new conversion
                else if (msg.type == "compiled")
                {
                    var _dataStr = "";
                    //console.log(msg);
                    
                    // Only set up the content area if this isn't a child 
                    if(msg.view == "child")
                    {
                       console.log("Child View");
                    }
                    else if(msg.content.schema=="dash")
                    {
                      // console.log("dash210");
                      var tdash="My: ";
                      for(i in msg.content.data)
                      {
                        tdash += '<a href="' + msg.content.data[i].ahref + '" id="'+ msg.content.data[i].TheID +'" class="dbut">' + msg.content.data[i].TheLabel 
                          + '<span class="dbstat">' + msg.content.data[i].TheStat + '</span></a> ';
                      }
                      // console.log(tdash);
                    $("#dashboard").html(tdash);
                    }
                    else
                    {
                       
                    $("#content").html('<div id="contenttitle" class="title"></div>' +
                    '<div id="menuArea"></div>' +
                    '<div class="title" id="dataSubtitle"></div>' +
                    '<div style="float: right;"><div id="filter"></div>' +
                    // Section for the filter
                    '<div id="dataArea"></div></div>'
                    // Section for the data
                    );
                    // Title - This means that the whole view will be reset.
                    if (msg.meta)
                    {
                       if(msg.meta.title) { $("#contenttitle").html(msg.meta.title); }
                       if (msg.meta.menu)
                       {
                           var mStr = "";
   
                           for (i in msg.meta.menu.menuItems)
                           {
                               if (msg.meta.menu.menuItems[i].menuTitle)
                               {
                                   mStr = mStr + '<div class="menuTile">' + msg.meta.menu.menuItems[i].menuTitle + '</div>';
                               }
   
                               for (j in msg.meta.menu.menuItems[i])
                               {
                                   if (j != "menuTitle")
                                   {
                                       mStr = mStr + '<div id="' + j + '" class="menuItem">' +
                                       msg.meta.menu.menuItems[i][j] +
                                       '</div>';
                                   }
                               }
                           }
                           $("#menuArea").append(mStr);
                       } 
                    }
                     if(msg.content.title)
                     {
                        //console.log(msg.content.title);
                        $("#dataSubtitle").html(msg.content.title); 
                     }
                     else
                     {
                        $("#dataSubtitle").hide();
                     }

                    } // End the if != child 

                    // Data
                    if (msg.content)
                    {
                        _dataStr = "";

                        // console.log(msg.content.title);
                        if (msg.content.title)
                        {
                            $("#dataSubtitle").html(msg.content.title);
                        }

                        if (msg.content.schema == "contacts")
                        {

                            _dataStr += '<div style="width: auto; background-color: #ddd; color: #333; padding: 3px 10px 3px 10px;border-bottom: 1px solid #444; font-size: 1.3em;">' +
                            'User <div style="text-align: right; float: right; margin-right: 10px; width: 125px;">' + msg.content.theStat + '</div></div>';

                            for (i in msg.content.data)
                            {
                                //console.log(i);
                                //console.log(msg.content.data[i].UserID);
                                // console.log(msg.content.data[i]);

                                _dataStr += '<div class="linkP" id="' + msg.content.data[i].UserID 
                                + '" style="width: auto; font-size: 1.4em; border-bottom: 1px solid #444; display: block; min-height: 50px;"> ' +
                                '<div style="width: 50px; height: 50px; float: left; background-image: url(\'https://graph.facebook.com/' 
                                + msg.content.data[i].fbuid + '/picture\')"></div>' +
                                msg.content.data[i].UserName + '<div style="width: 125px; float: right; font-size: 2.0em; text-align: right; margin-right: 10px;">' 
                                + msg.content.data[i].TheStat + '</div>' +
                                '</div>';
                            }
                        }


                        // console.log(msg.schema);
                        else if (msg.content.schema == "thing")
                        {
                            // Set the temp variables
                            var tmpP = 0;
                            var tmpL = 0;
                            var tmpT = 0;

                            for (i in msg.content.data)
                            {
                                // This will only show once.
                                if (i === 0)
                                {
                                    _dataStr += '<div class="level1">' +
                                    '<div class="addedNote">' + msg.content.data[i].Added +
                                    ' days ago</div><div class="linkT" id="' + msg.content.data[i].ThingID + '">' + msg.content.data[i].ThingName + '</div></div>';
                                }
                                // List 
                                if (tmpL != msg.content.data[i].ListID)
                                {
                                    // Do the person line
                                    _dataStr += '<div class="level2 linkL" id="' + msg.content.data[i].ListID + '">' + msg.content.data[i].ListName + '</div>';
                                    tmpL = msg.content.data[i].ListID;
                                    tmpP = 0;
                                    // Reset it for the next person
                                }
                                // Person
                                if (tmpP != msg.content.data[i].UserID)
                                {
                                    // Do the person line
                                    _dataStr += '<div class="level3 linkP" id="' + msg.content.data[i].UserID + '">' +
                                    '<div class="' + msg.content.data[i].inco +
                                    ' inc" id="' + _jsonpath + 'ditto/lu/' + msg.content.data[i].UserID + '/li/' + msg.content.data[i].ListID + '/lt/' 
                                    + msg.content.data[i].ThingID +
                                    '/"></div>' +
                                    '<div class="userIcon" style="background-image:url(\'https://graph.facebook.com/' + msg.content.data[i].fbuid + '/picture\');">' +
                                    '</div>' + msg.content.data[i].UserName + '</div>';

                                    tmpP = msg.content.data[i].UserID;
                                }
                            }

                        }
                        // 9/6/2010
                        else if (msg.content.schema == "lists")
                        {
                            // console.log("Lists schema");
                            // Set the temp variables
                            var tmpP = 0;
                            var tmpT = 0;
                            _dataStr += '<div style="width: auto; font-size: 1.2em; background-color: #333; color: #ccc; padding: 4px;">' +
                            '<span style="width: 400px; clear: none; ">List (Items)</span><span style="width: 100px;float: right;">Last Entry</span>' +
                            '</div>';
                            for (i in msg.content.data)
                            {
                                _dataStr += '<div id="' + msg.content.data[i].ParentListNameID 
                                + '" class="linkL" style="width: auto; font-size: 1.2em; border-bottom: 1px solid #444; padding: 4px;"'
                                + '<span style="width: 400px; ">' + msg.content.data[i].ThingName +' ('
                                + msg.content.data[i].TheCount + ')</span><span style="width: 100px; float: right;">' 
                                + msg.content.data[i].Modified + '</span></div>';
                            }


                        }
                        else if (msg.view == "user" || msg.view == "person")
                        {
                           // console.log("430");
                            // Handle the filter next.
                            function filterButtons(_key, _value)
                            {
                                var buttons = new Array("dittoable", "incommon", "all");
                                var str = '<ul class="buttons"><li style="border: 0px; color: #000;" id="filter/Text">Filter:</li>';
                                for (a in buttons)
                                {
                                    str = str + '<li class="feedFilter ' + buttons[a] + '" id="' + _key + '/' + _value + '/filter/' + buttons[a] + '/child/"></li>';
                                }

                                return str + '</ul>';
                            }

                            $("#filter").html(filterButtons("user", msg.UserID));

                            // Set the temp variables
                            var tmpP = 0;
                            var tmpL = 0;
                            var tmpT = 0;

                            for (i in msg.content.data)
                            {
                                // List 
                                if (tmpL != msg.content.data[i].ListID)
                                {
                                    // Do the person line
                                    _dataStr += '<div class="level2 linkL" id="' + msg.content.data[i].ListID + '">' + msg.content.data[i].ListName + '</div>';
                                    tmpL = msg.content.data[i].ListID;
                                }
                                // Always show the thing

                                _dataStr += '<div class="level3"><div class="' + msg.content.data[i].inco +
                                ' inc" id="' + _jsonpath + 'ditto/lu/' + msg.content.data[i].UserID + '/li/' + msg.content.data[i].ListID + '/lt/' + msg.content.data[i].ThingID +
                                '/"></div><div class="addedNote">' + msg.content.data[i].Added +
                                ' days ago</div><div class="linkT" id="' + msg.content.data[i].ThingID + '">' + msg.content.data[i].ThingName + '</div></div>';

                            }

                        }
                        else if (msg.content.schema == "feed")
                        {
                            // $("#filter").append("Filters: " + _tjp);

                            // Set the temp variables
                            var tmpP = 0;
                            var tmpL = 0;
                            var tmpT = 0;

                            if(msg.content.ListID)
                            {
                            _dataStr += "Add to <i>" + msg.content.ListName +
                            '</i><br/>' + addToList(msg.content.ListID) + '<br/>' +
                            '<div id="homefeed"></div>';
                            }
                            
                            if(msg.buttons)
                            {
                              _dataStr += filters( _tjp , msg.buttons);
                              
                            }

                            for (i in msg.content.data)
                            {
                                // User
                                if (tmpP != msg.content.data[i].UserID)
                                {
                                    // Do the person line
                                    _dataStr += '<div class="level1 linkP" id="' + msg.content.data[i].UserID + '">' +
                                    '<div class="userIcon" style="background-image:url(\'https://graph.facebook.com/' + msg.content.data[i].fbuid + '/picture\');">' +
                                    '</div>' + msg.content.data[i].UserName + '</div>';

                                    tmpP = msg.content.data[i].UserID;
                                    tmpL = 0;
                                    // Show the list for the next person
                                }
                                // List 
                                if (tmpL != msg.content.data[i].ListID)
                                {
                                    // Do the person line
                                    _dataStr += '<div class="level2 linkL" id="' + msg.content.data[i].ListID + '">' + msg.content.data[i].ListName + '</div>';
                                    tmpL = msg.content.data[i].ListID;
                                }
                                // Always show the thing
                                {
                                    _dataStr += '<div class="level3"><div class="' + msg.content.data[i].inco +
                                    ' inc" id="' + _jsonpath + 'ditto/lu/' + msg.content.data[i].UserID + '/li/' + msg.content.data[i].ListID + '/lt/' + msg.content.data[i].ThingID +
                                    '/"></div><div class="addedNote">' + msg.content.data[i].Added +
                                    ' days ago</div><div class="linkT" id="' + msg.content.data[i].ThingID + '">' + msg.content.data[i].ThingName + '</div></div>';
                                }
                            }

                        }

                        else if (msg.content.schema == "text")
                        {
                            for (i in msg.content.data)
                            {
                                if (msg.content.data[i].sub)
                                {
                                    _dataStr += '<div class="title">' + msg.content.data[i].sub + '</div>';
                                }
                                if (msg.content.data[i].p)
                                {
                                    _dataStr += '<p>' + msg.content.data[i].p + '</p>';
                                }
                            }

                        }
                        else
                        {
                            _dataStr += "unknown schema";
                        }
                        $("#dataArea").html(_dataStr);

                    }

                }
                else
                {
                    var _form = "";
                    // Is this a list? If yes, create the form element.
                    if (msg.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: Title 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>';
                        // Put the form in the HTML
                        $('#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)
                    {
                        if(msg.headers[0].title)
                        {
                        _title = msg.headers[0].title;
                        }
                    } else{
                        _title = "";
                    }

                    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.view);
                        if (msg.view == "person" || msg.view == "user")
                        {
                            $("#ui_viewMenu").html("User 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'>ERROR</div>No Results because the data from the server was being too silly");
                    // }
                }
            }
        });
    }

    /* Links to People, Lists, Things 7/2010 */
    $("div.linkP").live("click",
    function(){
        $("#content").html("Loading...");
        getData("#content", "user/" + $(this).attr('id') + "/");
        location.hash = "#/user/" + $(this).attr('id');
        $("a.navItem").removeClass("highlighted").addClass("notHighlighted");
             
    });
    
    $("div.searchR").live("click",
    function(){
        $('form').clearForm();
        console.log("Clicked Search R");
    });
    
    $("div.linkL").live("click",
    function(){
        $("#content").html("Loading...");
        getData("#content", "list/" + $(this).attr('id') + "/");
        location.hash = "#/list/" + $(this).attr('id');
        $("a.navItem").removeClass("highlighted").addClass("notHighlighted");
    });
    $("div.linkT").live("click",
    function(){
        $("#content").html("Loading...");
        getData("#content", "thing/" + $(this).attr('id') + "/");
        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);
        $("#dataArea").html("Loading...");
        // This is the parameter that gets sent to get the JSON
        getData("#dataArea", thisID + "/");
    });

    /* Menu Navigation */
    $("div.menuItem").live("click",
    function(){
        var _thisID = $(this).attr('id');
        // console.log("menu id" + $(this).attr('id'));
        $("#dataArea").html("Loading..." + _thisID);
        $("#filter").html("");
        getData("#dataArea", $(this).attr('id') + "/");
        // console.log("get data div: #dataArea, content: " +$(this).attr('id') );
        location.hash = "#/" + $(this).attr('id');
    });

    /* 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");
    });

    // Handle the main buttons
    $("a.dbut").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 + "/");

console.log(thisID);

        // Reset the active tabs
        $("a.dbut").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
        var ffJPath = $(this).attr("id");
        var ffCleaned = ffJPath.replace(/\//g, "\\/");
        // escape(ffJPath) doesn't work.

        $("#dataArea").html("Loading...");
        // console.log(ffCleaned);
        $("#" + ffCleaned).addClass("highlighted");

        // Clear, then re-add the highlighting for the filter.
        $("li.feedFilter").removeClass("highlighted");
        $("#" + ffCleaned).addClass("highlighted");

        getData("#dataArea", 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 if($(this).hasClass("me")){
            $(this).toggle().removeClass("me").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", "user/" + _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';
    }

});
