/**
 * Starting transition to curate module
 */

/*****************************************************************/
/* Defining the static curation module
/*****************************************************************/

if (typeof KIFFETS.curate == 'undefined' || !KIFFETS.curate) {
 KIFFETS.curate = 
    (function($) {
      var groupNum = 0;
      var entryIndex = 0;

      this.getMoreGroupNum = function() {
        return groupNum;
      };

      this.setMoreGroupNum = function(moreGroupNum) {
        groupNum = moreGroupNum;
      };

      this.getEntryIndex = function() {
        return entryIndex;
      };

      this.setEntryIndex = function(newIndex) {
        entryIndex = newIndex;
      };

      // Appends the given entries to the list of source results
      this.appendSourceEntries = function(sourceResultsDiv, entries, startIndex) {
        var counter = startIndex;
        for (var idx in entries) {
          var entry = entries[idx];

          var entryStr = '<DIV CLASS="sourceEntry"><INPUT CLASS="sourceCheckbox" TYPE="checkbox" NAME="entry'+counter+'" ID="entry'+counter+'" VALUE="'+encodeURIComponent(JSON.stringify(entry))+'" ONCLICK="KIFFETS.curate.toggleSourceEntry(\'entry'+counter+'\');"><SPAN CLASS="sourceEntryTitle"><A HREF="'+entry.sourceURL+'" TARGET="_blank">'+entry.sourceTitle+'</A></SPAN><BR><SPAN CLASS="sourceEntryURL">['+entry.sourceURL+']</SPAN><BR>';

          if (entry.articleURL) {
            entryStr += '<DIV CLASS="sampleArticle"><strong> Sample Article:</strong> <A CLASS="sampleArticleTitle" HREF="'+entry.articleURL+'" TARGET="_blank">'+entry.articleTitle+'</A> - '+entry.snippet+'</DIV>';
          } else {
            entryStr += '<DIV CLASS="sourceEntryDescription">'+entry.snippet+'</DIV>';
          }

          if (entry.hasOwnProperty('numMatchesPerMonth')) {
            entryStr += '<SPAN><STRONG>Keyword Matches Per Month:</STRONG> '+entry.numMatchesPerMonth+'</SPAN>';
          }

          sourceResultsDiv.append(entryStr);
          counter++;
        }
      };

      // function to Load more source results
      this.initLoadMoreSourceResults = function(sourceResultsDiv) {
        // Now add in a more button to get more results
        sourceResultsDiv.append('<DIV ID="sourceResultsMore">&lt;more&gt;</DIV>');

        var moreBtn = $('#sourceResultsMore', sourceResultsDiv);
        function clickCallback(evt) {
          var moreGroup = KIFFETS.curate.getMoreGroupNum();
          jQuery.ajax({
            type: 'POST',
                data: {'communityID': $('#findSourceCommID').attr('value'),
                  'q': unescape($('#findSourceQuery', sourceResultsDiv).text()),
                  'groupNum': moreGroup
                  },
                url: '/sourceFindMore/',
                success: function(responseTxt) {
                // Remove comment wrappers as needed
                var data = JSON.parse(stripComments(responseTxt));
                if (data.result == 'success') {
                  moreBtn.remove();
                  var entries = data.responseData.entries;
              
                  // Note that if we didn't get any new entries, then we remove the "more" button
                  if (entries.length > 0) {      
                    var indexPos = KIFFETS.curate.getEntryIndex();
                    sourceResultsDiv.append('<DIV CLASS="sourceResultMoreDivider">Results '+(indexPos+1)+' to '+(indexPos+entries.length)+'</DIV>');
                    KIFFETS.curate.appendSourceEntries(sourceResultsDiv, entries, indexPos);
                    KIFFETS.curate.setMoreGroupNum(moreGroup+1);
                    KIFFETS.curate.setEntryIndex(indexPos + entries.length);

                    sourceResultsDiv.append(moreBtn);
                    moreBtn.click(clickCallback);
                  } 
                } else {
                  sourceResultsDiv.append('<DIV>There was an error getting more resutls from the server</DIV>');
                }
              },
                error: function(requestObj, textStatus, errorThrown) {
                alert('There was an error adding sources on the server');
              }
            });      
        }

        moreBtn.click(clickCallback);

        return this;
      };

      // Function to reload the sources
      this.reloadSourcesList = function() {
        var channelName = KIFFETS.channel.getChannelName();

        jQuery.ajax({
          type: 'GET',
              url: '/i/'+encodeURIComponent(channelName)+'/sourcesListAjax/',
              success: function(responseTxt) {
              $('#channelSourcesList').html(responseTxt);
            },
              });
      };


      this.toggleSourceEntry = function(entryID) {
        var srcEntry = $('#'+entryID);
        var srcVal = srcEntry.attr('value');

        if (srcEntry.attr('checked')) {
          jQuery.ajax({
            type: 'POST',
                url: '/addSourceSubmit/',
                data: {'communityID': $('#findSourceCommID').attr('value'),
                  entryID: srcVal
                  },
                success: function(responseTxt) {
                // Remove comment wrappers as needed
                var data = JSON.parse(stripComments(responseTxt));
                if (data['result'] == 'success') {
                  KIFFETS.curate.reloadSourcesList();
                } else {
                  alert('There was an error adding sources on the server');
                }
              }
            });
        } else {
          jQuery.ajax({
              url: '/deleteSource/',
                type: 'POST',
                data: {'communityID': $('#findSourceCommID').attr('value'),
                  entryID: srcVal
                  },
                success: function (responseText) {
                  KIFFETS.curate.reloadSourcesList();
              },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('There was an error communicating with the server');
              }
            });        
        }
        };

      return this;
     })(jQuery);
}



function initializeFindSourcePage(successCallback) {
  ////////////////////////////////////////////////////////
  // Source related functions
  ////////////////////////////////////////////////////////

  function resetAddSourceForm(feedback) {
    $('#findSourceTextInput').val('');
    $('#findSourceResults').empty();
    $('#sourceResultsPlaceholder').css('display','block');
    $('#sourceResultsForm').css('display','none');
    $('#sourceResultsPlaceholder').css('color','red');
    $('#sourceResultsPlaceholder').html(feedback);
    scrollTo(0,0);
  }

  // These are the options passed to setup the add sources form
  var verifySrcFormOpts = {
    url: '/sourceFind/',
    beforeSubmit: function(formData, jqForm, options) {
      $('#findSourceResults').empty();                  

      $('#sourceResultsPlaceholder').css('display','none');
      $('#sourceResultsForm').css('display','none');

      return true;
    },
    success: function(responseTxt, statusTxt) {
      var data = JSON.parse(stripComments(responseTxt));
      if (data.result == 'failed') {
        $('#sourceResultsPlaceholder').css('display','block');
        $('#sourceResultsPlaceholder').css('color','red');
        $('#sourceResultsPlaceholder').text('There was an error processing your request - '+data.error);
      } else {
        var entries = data.responseData.entries;
        if (entries.length > 0) {

          //***************************************************************************//
          // Special case - if the user entered a feed directly (isSingleFeed), then
          // just add the feed and return
          if (entries.length == 1 &&
              entries[0].isSingleFeed) {
            jQuery.ajax({
              type: 'POST',
                  data: {'communityID': data.communityID,
                    'entry0': JSON.stringify({'sourceType': entries[0].sourceType,
                                                 'sourceURL': entries[0].sourceURL,
                                                 'sourceTitle': entries[0].sourceTitle})
                    },
                  url: '/addSourceSubmit/',
                  success: function(responseTxt) {
                  // Remove comment wrappers as needed
                  var data = JSON.parse(stripComments(responseTxt));
                  if (data['result'] == 'success') {
                    KIFFETS.curate.reloadSourcesList();

                    if (data['existing'].length > 0) {
                      resetAddSourceForm('The specified source has already been added to this channel.');
                    } else {
                      resetAddSourceForm('The specified source was added successfully.');
                    }

                    successCallback();
                  } else {
                    alert('There was an error adding sources on the server');
                  }
                },
                  error: function(requestObj, textStatus, errorThrown) {
                  alert('There was an error adding sources on the server');
                }
              });

            return;
          }
          //***************************************************************************//

          var counter = 0;
          var sourceResultsDiv = $('#findSourceResults');
          sourceResultsDiv.append('<DIV ID="findSourceQuery" STYLE="display: none;">'+escape(data.q)+'</DIV>');
          KIFFETS.curate.appendSourceEntries(sourceResultsDiv, entries, counter);
          KIFFETS.curate.setEntryIndex(entries.length);
          KIFFETS.curate.setMoreGroupNum(1);

          // URL queries won't have more results since we didn't go to the server for them
          if (!data.urlQuery) {
            KIFFETS.curate.initLoadMoreSourceResults(sourceResultsDiv);
          }

          $('#sourceResultsPlaceholder').css('display','none');
          $('#sourceResultsForm').css('display','block');
        } else {
          $('#sourceResultsPlaceholder').css('display','block');
          $('#sourceResultsPlaceholder').css('color','red');
          $('#sourceResultsPlaceholder').text('No Results Found!');
        }
      }                  
    },
    error: function(requestObj, textStatus, errorThrown) {
      alert('There was an error requesting sources from the server');
    },
    type: 'post'
  };            
  $('#sourceVerifyForm').ajaxForm(verifySrcFormOpts);

  var addSrcFormOpts = {
    url: '/addSourceSubmit/',
    beforeSubmit: function(formData, jqForm, options) {
      return true;
    },
    success: function(responseTxt, statusTxt) {
      // Remove comment wrappers as needed
      var data = JSON.parse(stripComments(responseTxt));
      if (data['result'] == 'success') {
        KIFFETS.curate.reloadSourcesList();

        if (data['existing'].length == 0) {
          resetAddSourceForm('The selected sources were added successfully.');
        } else if (data['new'].length == 0) {
          resetAddSourceForm('The selected sources have already been added to this channel.');
        } else {
          var feedbackStr = 'The following sources were added successfully:<UL>';
          for (i in data['new']) {
            feedbackStr += '<LI>'+data['existing'][i]+'</LI>';
          }
          feedbackStr += '</UL>The following sources have already been added to this channel:<UL>';
          for (i in data['existing']) {
            feedbackStr += '<LI>'+data['new'][i]+'</LI>';
          }
          feedbackStr += '</UL>';

          resetAddSourceForm(feedbackStr);
        }
        

        successCallback();
      } else {
        alert('There was an error adding sources on the server');
      }
    },
    error: function(requestObj, textStatus, errorThrown) {
      alert('There was an error adding sources on the server');
    },
    type: 'post'
  };            
  $('#sourceResultsForm').ajaxForm(addSrcFormOpts);
}

function initializeAddTopicPage(indexName, successCallback) {
  ////////////////////////////////////////////////////////
  // Add topic init functions
  ////////////////////////////////////////////////////////

  // Initialize the topic tree, if there is one.  There won't be 
  // a topic tree if there is only one topic
  var topicTree = $("#refineTopicTree");
  if (topicTree.length > 0) {
    // If more than one topic, include a tree to select
    // one of the topics

    function labelSelector(evt) {
      var node = $(evt.currentTarget);

      var selectedNode = $('#refineTopicTree .selected');
      if (selectedNode.length > 0) {
        selectedNode.removeClass('selected');
      }
                
      node.addClass('selected');
                
      return false;
    } 

    topicTree.treeview({
      collapsed: true,
          animated: "medium",
          prerendered: true,
          persist: "location"
          });
    $('[id^=topic_]',topicTree).click(labelSelector);              
  }

  // These are the options passed to setup the add topic form
  var addTopicFormOpts = {
    type: 'POST',
    url: '/i/'+encodeURIComponent(indexName)+'/addTopicSubmitAjax/',
    beforeSubmit: function(formData, jqForm, options) {
      var userTopicName = $('#indexTunerTopicName').val();
      if (userTopicName.length == 0) {
        var alertNode = $('#addTopicAlert');
        alertNode.css('display', 'block');
        alertNode.text('The new topic name cannot be empty');
        return false;
      }

      var parentInput = $('#parentTopicIDInput');
      if (parentInput.length == 0) {
        // If there is one topic, then it will be preselected in the form data
        // - otherwise, we manually push the form data
        var selectedNode = $('#refineTopicTree .selected');
        if (selectedNode.length == 0) {
          var alertNode = $('#addTopicAlert');
          alertNode.css('display', 'block');
          alertNode.text('Please select a parent for the new topic');
          return false;
        }
        
        var fullTopID = selectedNode.attr('id');
        var topicID = fullTopID.substring(fullTopID.indexOf('_')+1);
        formData.push({'name':'parentID','value':topicID});
      }

      $('#addTopicSubmit').attr('disabled','true');
      return true;
    },
    success: function(responseTxt, statusTxt) {
      var data = JSON.parse(stripComments(responseTxt));
      if (data['result'] == 'success') {
        successCallback(data['topicID']);
      }
    },
    error: function(requestObj, textStatus, errorThrown) {
      alert('There was an error starting the topic on the server');
    }
  };            
  $('#addTopicForm').ajaxForm(addTopicFormOpts);
}


function initializeAddTopicQSPage(successCallback) {
  ////////////////////////////////////////////////////////
  // Add topic quickstart init functions
  ////////////////////////////////////////////////////////

  // These are the options passed to setup the add topic form
  var addTopicFormOpts = {
    url: '/quickStartTopic/',
    beforeSubmit: function(formData, jqForm, options) {
      $('#topicExampleResults').empty();                 
      $('#topicResultsPlaceholder').css('visibility','hidden');
      $('#topicResultsForm').css('visibility','hidden'); 
      return true;
    },
    success: function(responseTxt, statusTxt) {
      $('#topicExampleResults').html(responseTxt);

      $('#topicResultsPlaceholder').css('visibility','hidden');
      $('#topicResultsForm').css('visibility','visible');
    },
    error: function(requestObj, textStatus, errorThrown) {
      alert('There was an error starting the topic on the server');
    },
    type: 'post'
  };            
  $('#addTopicForm').ajaxForm(addTopicFormOpts);

  var topicSelectFormOpts = {
    url: '/quickStartTopicSelect/',
    beforeSubmit: function(formData, jqForm, options) {
      return true;
    },
    success: function(responseTxt, statusTxt) {
      // Remove comment wrappers as needed
      var data = JSON.parse(stripComments(responseTxt));
      if (data['result'] == 'success') {
        successCallback(data['topicID']);
      } else {
        alert('There was an error adding a topic on the server');
      }
    },
    error: function(requestObj, textStatus, errorThrown) {
      alert('There was an error adding a topic on the server');
    },
    type: 'post'
  };            
  $('#topicResultsForm').ajaxForm(topicSelectFormOpts);

  $('#topicExampleCommID').attr('value',$('#indexNameNode').text());

}


