// NOTE - Starting to convert Kiffets variables to put everything in a kiffets namespace

(function($) {
  $.extend(KIFFETS.core, {
      /*******************************************************/
      /*                                                     */
      /* Setup functions for controls on the topic tree      */
      /*                                                     */
      /*******************************************************/

      /**
       * Setup the topic controls popup window that is shown on hover in the topic tree
       */
    setupTopicControlsPopup: function(callback) {
               // Setup the topic controls popup to dismiss itself on hover out
               var popupNode = $('#topicControlsPopup');

               popupNode.hover(function(evt) {
                                 // Hover in
                                 if (KIFFETS.core.currentHoverTimeoutID) {
                                   window.clearTimeout(KIFFETS.core.currentHoverTimeoutID);
                                   KIFFETS.core.currentHoverTimeoutID = 0;
                                 }
                               },
                               function (evt) {
                                 // Hover out
                                 popupNode.css('display','none');
                                 if (callback) {
                                   callback();
                                 }
                               });
             },

               topicTreeHoverIn: function(hoverCallback) {
               return function(evt) {
                 if (KIFFETS.core.currentHoverTimeoutID) {
                   window.clearTimeout(KIFFETS.core.currentHoverTimeoutID);
                   KIFFETS.core.currentHoverTimeoutID = 0;
                 }

                 var currentNode = $(evt.currentTarget);

                 var popupNode = $('#topicControlsPopup');
                  
                 var nodeTop = currentNode.offset().top-$('.indexLeftBar').offset().top - 6;
                 var nodeRightLimit = Math.min(175, currentNode.offset().left+currentNode.width() + 2);
                 popupNode.css('top',nodeTop);
                 popupNode.css('left',nodeRightLimit);
                 popupNode.css('display','block');

                 if (hoverCallback) {
                   hoverCallback(currentNode);
                 }
               };
             },
	      
               topicTreeHoverOut: function(hoverCallback) {
               return function(evt) {
                 KIFFETS.core.currentHoverTimeoutID = window.setTimeout(function() {
                                                                          $('#topicControlsPopup').css('display','none');
                                                                          KIFFETS.core.currentHoverTimeoutID = 0;
                                                                          if (hoverCallback) {
                                                                            hoverCallback(null);
                                                                          }
                                                                        }, 250); 
               };
             },

               /**
                * Setup the topic controls popup - this assumes that a topic tree is loaded
                * on the page. And that the topicControlsPopup is also loaded on the page.
                */
               setupTopicControls: function(parentDiv, hoverCallback) {
               // Setup the topic controls popup to dismiss itself on hover out
               var popupNode = $('#topicControlsPopup');

               // Set the border red for superusers
               if ($('#isIndexOwner').length > 0) {
                 popupNode.css('border-color','black');
               } else if ($('#isSuperuser').length > 0) {
                 popupNode.css('border-color','#ff5900');		  
               }

               $('a[id^=topic_]',parentDiv).hover(KIFFETS.core.topicTreeHoverIn(hoverCallback), KIFFETS.core.topicTreeHoverOut(hoverCallback));
             },

               /*******************************************************/
               /*                                                     */
               /* On topic/ Off topic / Different topic               */
               /*                                                     */
               /*******************************************************/

               /**
                * Send the article as an example on a different topic
                */
               sendArticleToTopic: function(channelName, articleID, reloadNew) {
               jQuery.ajax({
                 type: 'GET',
                     url: '/i/'+channelName+'/classifyArticleDialog/'+articleID+'/',
                     data: {},
                     success: function(data) {
                     // Create the classification popup and add it to the 
                     // display
                     var topicTreePopup = $(data);
                     $('body').append(topicTreePopup);
                     topicTreePopup.jqm({modal:false, 
                                            onHide: function(hash) {
                                            hash.o.remove();
                                            topicTreePopup.remove();
                                          }});

                     $('#classifyDlgCloser').click(function(evt) {
                                                     topicTreePopup.jqmHide();
                                                   });


                     var artID = $('#classifyArticleID', topicTreePopup).text();
                     var presetTopicID = -1;

                     // Now add our listeners 
				
                     // If there is a tree, then we have a multi-topic index
                     // - otherwise, the root will be selected
                     var currentTreeNode = null;
                     var topicTree = $("#classifyTopicTree");
                     if (topicTree.length > 0) {
                       topicTree.treeview(
                                          {collapsed: true,
                                              animated: "medium",
                                              prerendered: true,
                                              persist: "location",
                                              url: "/i/"+channelName+"/topicChildrenNTAjax/"
                                              });

                       topicTreePopup.find('[id^=topic_]', topicTreePopup).click(
                                                                                 function(evt) {
                                                                                   var newNode = $(evt.currentTarget);

                                                                                   if (currentTreeNode) {
                                                                                     currentTreeNode.removeClass('selected');
                                                                                   }
				      
                                                                                   newNode.addClass('selected');			     
                                                                                   currentTreeNode = newNode;
                                                                                 });
                     } else {
                       var rootTopicNode = topicTreePopup.find('#classifyRootTopicID');
                       presetTopicID = rootTopicNode.text();
                     }

                     // Little wrapper function to get the current topic
                     // based on the context
                     function getSelectedTopicID() {
                       var topicID = -1;
                       if (presetTopicID != -1) {
                         topicID = presetTopicID;
                       } else if (currentTreeNode) {
                         var fullTopID = currentTreeNode.attr('id');
                         topicID = fullTopID.substring(fullTopID.indexOf('_')+1);
                       }
                       return topicID;			   
                     }
				
                     // Add a listener on the add in selected topic button
                     topicTreePopup.find('#addInSelectedTopic').click(
                                                                      function(evt) {
                                                                        var alertNode = $('#classifyAlert');

                                                                        var topicID = getSelectedTopicID();
                                                                        if (topicID == -1) {
                                                                          alertNode.text('Please select a topic');
                                                                          alertNode.css('display','block');
                                                                          return;
                                                                        } 

                                                                        alertNode.css('display','none');
				    
                                                                        var requestObj = {'articleID': artID,
                                                                                          'communityName': channelName,
                                                                                          'topicID': topicID};
				    
                                                                        jQuery.ajax({type: 'POST',
                                                                                        url: '/sendArticleToTopic/', 
                                                                                        data: requestObj,
                                                                                        error: function(request, textStatus, errorThrown) {
                                                                                        alertNode.html(request.responseText);
                                                                                        alertNode.css('display','block');
                                                                                      },
                                                                                        success: function (data, textStatus) {
                                                                                        topicTreePopup.jqmHide();
                                                                                      }
                                                                                    });
				    
                                                                      });

                     // Add a listener on the add in new topic button
                     topicTreePopup.find('#addInNewTopic').click(
                                                                 function(evt) {
                                                                   var alertNode = $('#classifyAlert');

                                                                   var topicID = getSelectedTopicID();
                                                                   if (topicID == -1) {
                                                                     alertNode.text('Please select a parent topic for the new subtopic');
                                                                     alertNode.css('display','block');
                                                                     return;
                                                                   } 			     

                                                                   KIFFETS.core.iePrompt('Enter a name for the new topic:', function promptCallback(val) {
                                                                                           if (val == null) {
                                                                                             return;
                                                                                           } else if (val == '') {
                                                                                             alert('Topic name cannot be empty');
                                                                                             return;
                                                                                           }

                                                                                           var requestObj = {'articleID': artID,
                                                                                                             'communityName': channelName,
                                                                                                             'topicID': topicID,
                                                                                                             'createTopicName': val};
							    
                                                                                           jQuery.ajax({type: 'POST',
                                                                                                           url: '/sendArticleToTopic/', 
                                                                                                           data: requestObj,
                                                                                                           error: function(request, textStatus, errorThrown) {
                                                                                                           alertNode.html(request.responseText);
                                                                                                           alertNode.css('display','block');
                                                                                                         },
                                                                                                           success: function (data, textStatus) {
                                                                                                           topicTreePopup.jqmHide();
                                                                                                           if (reloadNew) {
                                                                                                             location.reload();
                                                                                                           }
                                                                                                         }
                                                                                                       });
                                                                                         });

                                                                 });

                     // And ... we show the popup
                     topicTreePopup.jqmShow();
                   }, 
                     dataType: 'html',
                     error: function(request, textStatus, errorThrown) {
                     loadHTML(request.responseText);
                   }
                 });	   
             },

               // Functions for getting and setting the current popup video
               popupYoutubeID: '',
               setPopupYoutubeID: function(newID) {
               KIFFETS.core.popupYoutubeID = newID;
             },
               getPopupYoutubeID: function() {
               return KIFFETS.core.popupYoutubeID;
             }
    });
 })(jQuery);


/*******************************************************/
/*                                                     */
/* Logout, login, and help methods                     */
/*                                                     */
/*******************************************************/

function doLogin() {
  $('#registerDlg').jqmShow();
  return false;
}

function doLogout(dest) {
  jQuery.post( '/json/1.0/', 
               "request="+JSON.stringify({'methodName': 'logout'}), 
               function() {
                 if (dest) {
                   location = dest;
                 } else {
                   location.reload();
                 }
               });  
}

function showHelpDialog() {
  $('#helpDlg').jqm({
    onLoad:function(hash) {                         
        function helpDlgCloser() {
          $('#helpDlg').jqmHide();     
        }                  
        $('#helpCloser').click(helpDlgCloser);
        $('#helpOKButton').click(helpDlgCloser);
        
        hash.w.show();
      }
    });
  $('#helpDlg').jqmShow();  
}

/**
 * Setup the email form on the email article dialog
 */
function setupEmailForm(hash) {
  // These are the options passed to setup the register form
  var eFormOpts = {
    url: '/emailArticle/',
    beforeSubmit: function(formData, jqForm, options) {
      var emailAddy = $('#emailArticleAddress').attr('value');
      if (isEmailReasonable(emailAddy)) {
        return true;
      } else {
        if (emailAddy.length > 0) {
          $('#emailArticleAlert').text('That email address does not appear to be valid');
        } else {
          $('#emailArticleAlert').text('Please specify an email address');
        }
        $('#emailArticleAlert').css('display', 'block');
        return false;
      }
    },
    success: function(responseTxt, statusTxt) {
      $('#emailArticleFormDiv').css('display','none');
      $('#emailArticleResult').css('display','block');

      var result = JSON.parse(stripComments(responseTxt));
      if (result['result'] == 'success') {
        $('#emailArticleResultMessage').text('Your article will be sent shortly!');
      } else {
        if (result.message) {
          $('#emailArticleResultMessage').text(result.message);        
        } else {
          $('#emailArticleResultMessage').text('There was an error handling your request');        
        }
      }
    },
    error: function(requestObj, textStatus, errorThrown) {
      alert('There was an error communicating with the Kiffets server.');
    },
    type: 'post'
  };            
  $('#emailArticleForm').ajaxForm(eFormOpts);
              
  $('#emailArticleCancel').click(function() {
                                   $('#emailDlg').jqmHide();
                                   return false;
                                 });  
  $('#emailArticleResultOK').click(function() {
                                     $('#emailDlg').jqmHide();
                                     return false;
                                   });
}

function emailArticle(articleID, indexID) {  
  if ($('#usernameEl').length == 0) {
    doLogin();
    return;
  }

  var titleNode = $('#article_title_'+articleID);
  var descNode = $('#article_description_'+articleID);
  
  var titleTxt = titleNode.text();
  var urlTxt = titleNode.attr('href');

  $('#emailDlg').jqm({onLoad:function(hash) {
                         setupEmailForm(hash);

                         $('#emailArticleID').attr('value', articleID);
                         $('#emailIndexID').attr('value', indexID);

                         // Set the article details on the dialog link
                         $('#emailArticleTitle').text(titleTxt);
                         $('#emailArticleTitle').attr('href', urlTxt);
                         
                         hash.w.show();
                       }});
  $('#emailDlg').jqmShow();  
}

function postOnFacebook(articleID, indexID) {
  var titleNode = $('#article_title_'+articleID);
  var descNode = $('#article_description_'+articleID);

  var titleTxt = titleNode.text();
  var urlTxt = titleNode.attr('href');

  // In titles-only view, the description may not exist
  var descTxt = '';
  if (descNode.length > 0) {
    descTxt = descNode.text();
  }
  
  postStoryToFacebook(urlTxt, titleTxt, descTxt, indexID);
}

/**
 * Method to post a story to facebook.  Requires that page include the
 * facebook script
 */
function postStoryToFacebook(url, title, description, indexID) {
  var kiffURL = 'http://apps.facebook.com/kiffets/';
  if (indexID) {
    kiffURL += '?indexID='+indexID;
  }

  // 240 Seems to be the magic number where Facebook cuts us off
  // -- NOTE that title is guaranteed to be less than 240 because
  // of our DB schema limits, so we are safe not to trim the title
  //
  // We trim the title+desc ourselves so that the "more like this"
  // line shows up at the bottom.  Otherwise, it gets hidden by a
  // "Read more" link on Facebook.
  if (title.length + description.length > 240) {
    description = description.substring(0,240-title.length)+'...';
  }

  
  FB_RequireFeatures(['Connect'], function() {
                       FB.Facebook.init('348e53c74cf743b9c8144ddaf37f2676', "/media/html/xd_receiver.htm");
                       FB.Connect.requireSession(function() {
                                                   FB.Connect.streamPublish('', 
                                                                            {'media':[{'type': 'image', 'src': 'http://kiffets.com/media/img/kiffets-beta-cs_75.gif', 'href': kiffURL}], 
                                                                                'name': title,
                                                                                'href': url,
                                                                                'description': description},
                                                                            null,
                                                                            null,
                                                                            'Comments on this article:',
                                                                            function(post_id, exception) {});
                                                                            
                                                   //                                                   FB.Connect.showFeedDialog(265278965580, {'images':[{'src':'http://kiffets.com/media/img/kiffets-beta-cs_75.gif','href':kiffURL}],'title':title, 'url':url, 'kiffURL':kiffURL,'description':description}, null, null, null, FB.RequireConnect.promptConnect, function(postId, exception, data) {});
                                                 });
                     });
};

/*******************************************************/
/*                                                     */
/* Video related functions                             */
/*                                                     */
/*******************************************************/

/* Play the specified youtube video */
function playYoutubeVideo(id, autoplay, playDiv, hideDiv, backText) {
  var pDiv = $('#'+playDiv);
  var backHTML = '';
  if (hideDiv) {
    var hDiv = $('#'+hideDiv);
    hDiv.css('display', 'none');
    
    if (backText) {
      backHTML = '<A STYLE="padding-top: 10px;" HREF="#" ONCLICK="stopVideo(\''+playDiv+'\',\''+hideDiv+'\')">'+backText+'</A>';
    }
  }

  var url = 'http://www.youtube.com/v/'+id+'&hl=en_US&fs=1&rel=0&border=1'+((autoplay) ? '&autoplay=1' : '');

  var width=640;
  var height=405;

  pDiv.html('<div style="text-align:center;"><object width="'+width+'" height="'+height+'"><param name="movie" value="'+url+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+url+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'+width+'" height="'+height+'"></embed></object> <div>'+backHTML+'</div></div>');

  pDiv.css('display', 'block');

  return false;
}

/* Stop the video and clear the video element */
function stopVideo(videoDiv, contentDiv) {
  $('#'+videoDiv).empty();
  $('#'+contentDiv).css('display','block');
}

/*******************************************************/
/*                                                     */
/* Subscription and on/off topic related functions     */
/*                                                     */
/*******************************************************/

function subscribe(commName, noReload) {
  jQuery.post( '/json/1.0/', 
               "request="+JSON.stringify({'methodName': 'subscribeCommunity', 'community': commName}), 
               function() {
                 if (!noReload) {
                   location.reload();
                 }
               });  
}

function unsubscribe(commName, noReload) {
  jQuery.post( '/json/1.0/', 
               "request="+JSON.stringify({'methodName': 'unsubscribeCommunity', 'community': commName}), 
               function() {
                 if (!noReload) {
                   location.reload();
                 }
               });    
}


function markOnTopic(topicID, articleID) {
  var otEl = $('#ontopic_'+topicID+'_'+articleID);
  if (otEl.hasClass('onTopicButton')) {
    jQuery.post( '/json/1.0/', 
                 'request='+JSON.stringify({'methodName': 'markOnTopic', 'topicID': topicID, 'articleID': articleID}), 
                 function(data) {
                   otEl.children('.onTopicIcon').hide();
                   otEl.removeClass('onTopicButton');
                   otEl.addClass('onTopicButtonDisabled');
                 });
  } 
}

function markOffTopic(topicID, articleID) {
  var otEl = $('#offtopic_'+topicID+'_'+articleID);
  if (otEl.hasClass('offTopicButton')) {
    jQuery.post( '/json/1.0/', 
                 'request='+JSON.stringify({'methodName': 'markOffTopic', 'topicID': topicID, 'articleID': articleID}), 
                 function(data) {
                   otEl.children('.offTopicIcon').hide();
                   otEl.removeClass('offTopicButton');
                   otEl.addClass('offTopicButtonDisabled');
                 });
  }
}




/*******************************************************/
/*                                                     */
/* Some generic modal popups - we use these instead of */
/* prompt and confirm since we can add HTML styling    */
/*                                                     */
/*******************************************************/

function showPromptPopup(promptTitle, promptVal, callback) {
  var inputPopup = $('#genericInputPopup');

  inputPopup.data('callback',callback);
  $('#genericInputPopupConfirmContent').css('display','none');
  $('#genericInputPopupAlertContent').css('display','none');
  $('#genericInputPopupPromptContent').css('display','block');
  $('#genericInputPopupPromptTitle').html(promptTitle);
  $('#genericInputPopupText').val(promptVal);

  inputPopup.jqmShow();
}

function showConfirmPopup(confirmTitle, callback) {
  var inputPopup = $('#genericInputPopup');

  inputPopup.data('callback',callback);  
  $('#genericInputPopupConfirmContent').css('display','block');
  $('#genericInputPopupAlertContent').css('display','none');
  $('#genericInputPopupPromptContent').css('display','none');
  $('#genericInputPopupConfirmTitle').html(confirmTitle);

  inputPopup.jqmShow();
}


function showAlertPopup(alertTitle, callback) {
  var inputPopup = $('#genericInputPopup');

  inputPopup.data('callback',callback);  
  $('#genericInputPopupAlertContent').css('display','block');
  $('#genericInputPopupConfirmContent').css('display','none');
  $('#genericInputPopupPromptContent').css('display','none');
  $('#genericInputPopupAlertTitle').html(alertTitle);

  inputPopup.jqmShow();
}

function genericInputOKCallback() {
  var inputPopup = $('#genericInputPopup');
  inputPopup.jqmHide();

  var callback = inputPopup.data('callback');
  if (callback) {
    callback($('#genericInputPopupText').val());
  }
}

function genericInputCancelCallback() {
  var inputPopup = $('#genericInputPopup');
  var callback = inputPopup.data('callback');
  if (callback) {
    inputPopup.jqmHide();
    callback(null);
  }  
}

function genericInputYesCallback() {
  var inputPopup = $('#genericInputPopup');
  var callback = inputPopup.data('callback');
  if (callback) {
    inputPopup.jqmHide();
    callback(true);
  }  
}

function genericInputNoCallback() {
  var inputPopup = $('#genericInputPopup');
  var callback = inputPopup.data('callback');
  if (callback) {
    inputPopup.jqmHide();
    callback(false);
  }  
}

function genericInputAlertOKCallback() {
  var inputPopup = $('#genericInputPopup');
  inputPopup.jqmHide();

  var callback = inputPopup.data('callback');
  if (callback) {
    callback();
  }
}


/**
 * Basic rename functionality that does basic detection and calls the specified
 * callback on success
 */
function renameTopicBase(indexName, renameTopic, callbackParam, promptOverride) {
  var topicID = renameTopic.data('topicID');

  var promptTxt = (promptOverride) ? promptOverride : 'Please enter a new name for "'+renameTopic.data('name')+'"';
  promptTxt = (promptOverride || topicID != '0') ? promptTxt : promptTxt + ' -- <SPAN STYLE="color: #ff5900; font-weight: bold;">Note that renaming the root topic will also rename the Index.</SPAN>';

  /**
   * We use a custom HTML-based prompt - so we have to handle the result in a callback
   */
  function renameCallback(newName) {
    newName = (newName) ? $.trim(newName) : newName;

    // Make sure the new topic name isn't empty
    if (newName != null &&
        newName.length == 0) {
      renameTopicBase(indexName, renameTopic, callbackParam, 'The new name cannot be empty. Please enter a new name for "'+renameTopic.data('name')+'"');
      return;
    }

    if (topicID == '0') {
      if (newName != null &&
          newName != renameTopic.data('name')) {
        jQuery.ajax({
          type: 'POST',
              url: '/json/1.0/', 
              data: {'request':JSON.stringify({
                  'methodName': 'renameCommunity',
                    'communityName': renameTopic.data('name'),
                    'newName': newName})},
              success: function(data) {
              // Successfully renamed the topic on the server
              var result = JSON.parse(stripComments(data));
              if (result['result'] == 'success') {                
                callbackParam(newName);                
              } else {
                // This name is probably taken
                renameTopicBase(indexName, renameTopic, callbackParam, 'The name "'+newName+' is already in use!  Each Index must have a unique name.  Please enter a new name.');
              }
            }, 
              error: function(request, textStatus, errorThrown) {
            }
          });      
      }
    } else {
      if (newName != null &&          
          newName != renameTopic.data('name')) {

        jQuery.ajax({
          type: 'POST',
              url: '/json/1.0/', 
              data: {'request':JSON.stringify({
                  'indexName': indexName,
                    'methodName': 'updateModifiedTopics',
                    'modifiedTopics': [{'id':topicID,'name':newName}]})},
              success: function(data) {
              // Successfully renamed the topic on the server
              var result = JSON.parse(stripComments(data));
              if (result['modifiedTopics'] &&
                  result['modifiedTopics'][topicID]) {                
                callbackParam(newName);
              }
            }, 
              error: function(request, textStatus, errorThrown) {
            }
          });      
      }
    }
  }

  // Actually ask the user for the new name
  showPromptPopup(promptTxt, renameTopic.data('name'), renameCallback);
}

function addChildBase(indexName, parentTopic, callbackParam, promptOverride) {
  var parentID = parentTopic.data('topicID');

  var promptTxt = (promptOverride) ? promptOverride : "Please enter a name for the new topic";
  
  function addTopicCallback(newName) {
    newName = (newName) ? $.trim(newName) : newName;

    if (newName != null &&
        newName.length == 0) {
      // If the new name is empty, then treat this as a cancel
      addChildBase(indexName, parentTopic, callbackParam, "The new topic name cannot be empty. Please enter a name for the new topic");
      return;
    } else {
      jQuery.ajax({
        data: {'parentID': parentID, 'topicName': newName},
            url: '/i/'+encodeURIComponent(indexName)+'/addTopicSubmitAjax/',
            success: function(responseTxt, statusTxt) {
            var data = JSON.parse(stripComments(responseTxt));
            if (data['result'] == 'success') {
              callbackParam(data['topicID']);
            }
          },
            error: function(requestObj, textStatus, errorThrown) {
            alert('There was an error starting the topic on the server');
          }
        });
    }
  }

  // Actually ask the user for the new name
  showPromptPopup('Please enter a name for the new topic', '', addTopicCallback);  
}

/**
 * Basic delete topic functionality - calls the specified callback on success
 */
function deleteTopicBase(indexName, delTopic, delCallback) {
  var topicID = delTopic.data('topicID');

  if (topicID == '0') {
    function deleteChannelCallbackWrapper(shouldDelete) {        

      if (shouldDelete) {
        jQuery.ajax({
          type: 'POST',
              url: '/json/1.0/', 
              data: {'request':JSON.stringify({
                  'methodName': 'deleteCommunity',
                    'communityName': indexName})},
              success: function(data) {
              // Successfully deleted the community on the server
              var result = JSON.parse(stripComments(data));
              if (result['result'] == 'success') {
                delCallback();
              }
            }, 
              error: function(request, textStatus, errorThrown) {
            }
          });      
      }
    }

    showConfirmPopup('<SPAN STYLE="color: #ff5900; font-weight:bold; font-size: 1.2em;">Deleting the root topic will delete the Channel!</SPAN>  Do you really want to do this?', deleteChannelCallbackWrapper);

  } else {
    function deleteTopicCallbackWrapper(shouldDelete) {        
      if (shouldDelete) {
        jQuery.ajax({
          type: 'POST',
              url: '/json/1.0/', 
              data: {'request':JSON.stringify({
                  'methodName': 'updateModifiedTopics',
                    'indexName': indexName,
                    'deletedTopicIDs': [topicID]})},
              success: function(data) {
              // Successfully deleted the topic on the server
              var result = JSON.parse(stripComments(data));
              if (result['deletedTopicIDs'] &&
                  result['deletedTopicIDs'].indexOf(topicID) != -1) {
                delCallback();
              }
            }, 
              error: function(request, textStatus, errorThrown) {
            }
          });      
      }
    }
      
    // Count how many topic's we'll be deleting
    var subCount = $('[id^=topic_]',KIFFETS.core.currentHoverTopicNode).length;
    var promptTxt = 'Do you really want to delete topic "'+KIFFETS.core.currentHoverTopicNode.data('name')+'"';
    promptTxt = (subCount) ?  promptTxt + ' and '+subCount+' subtopics?' : promptTxt +'?';
      
    showConfirmPopup(promptTxt, deleteTopicCallbackWrapper);
  }  
}

/*******************************************************/



/* Called when the page is loaded */
$().ready(function() {

            ////////////////////////////////////////////////////////
            // Login related functions
            ////////////////////////////////////////////////////////

            var rSetup = function(hash) {
              setupRegisterForm('registerForm', 'registerAlert', '/channelProfiles/','/registerPublic/');
              setupLoginForm('popupLoginForm', 'registerLoginAlert', null);
            };            


            // Initialize our login form
            $('#registerDlg').jqm({ajax: '/registerDialog/', trigger: 'a.loginTrigger', onLoad: rSetup });

            setupLoginForm('loginForm', 'baseLoginAlert', null);

            // Show the small login form when the user clicks login
            $('#showLogin').click(function() {
                                    $('#loginFormBox').slideDown('fast');
                                    return false;
                                  });
            $('#hideLogin').click(function() {
                                    $('#loginFormBox').slideUp('fast');
                                  });


            ////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////
            // Initialize the email popup
            ////////////////////////////////////////////////////////

            // Initialize the email popup
            $('#emailDlg').jqm({ajax: '/emailDialog/', modal: true });
            
            ////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////
            // Initialize the intro popup
            ////////////////////////////////////////////////////////

            // Initialize our intro popup
            $('#helpDlg').jqm({ajax: '/helpDialog/', overlay: 50, trigger: false, modal: false});

            ////////////////////////////////////////////////////////


            // Initialize the video popup
            var videoLoader = function (hash) {
              playYoutubeVideo(KIFFETS.core.getPopupYoutubeID(),true,'videoDlgContent');
              hash.w.show();
            };

            var videoHider = function (hash) {
              $('#videoDlgContent').empty();
              hash.o.remove();
              hash.w.hide();
            }
            
            $('#videoDlg').jqm({overlay: 50, modal: false, onShow: videoLoader, onHide: videoHider});
            $('#videoDlg').jqmAddClose('#videoDlgCloser');
            $('#videoDlg').jqmAddClose('#videoDlgOKButton');

            $('#topVideoDisplayer').click(function(evt) {
                                            KIFFETS.core.setPopupYoutubeID('uvPPVGcWQ6Y');
                                            $('#videoDlg').jqmShow();
                                            return false;
                                          });

            ////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////
            // Initialize the generic popup
            ////////////////////////////////////////////////////////

            /* Initialize the generic input dialog - used for topic controls */
            $('#genericInputPopup').jqm({'modal':true});

            ////////////////////////////////////////////////////////            
          });

