/**
 * @author Bruno
 */
function fileTypeToTypeString(type){
  if (("suspicious" == type) || ("susp" == type) || (2 == type) || ("2" == type)) 
    return "suspicious";
  else 
    return "reference";
}



function removeFile(type, id){
  // the easy way
  var data = {
    action: "removeFile",
    fileId: id
  };
  
  showLoading();
  
  $.get("", data, function(response){
    // @todo: check the answer
    hideLoading();
    updateFileDatabase(type);
  });
}


function viewFileContents(type, id){
  var file = null;
  
  for (f in fileDatabaseItems[type]) {
    if (fileDatabaseItems[type][f].id == id) {
      file = fileDatabaseItems[type][f];
      break;
    }
  }
  
  
  if (file == null) {
    window.alert("File not found!");
    return;
  }
  
  var data = {
    action: "getParsedFileContents",
    fileId: id
  };
  
  
  var textWindow = "<div id='text-view' title='" + file.filename + "'><p style='white-space:pre-wrap; font-size: smaller'></p></div>";
  $("body").append(textWindow);
  $("#text-view").dialog({
    autoOpen: false,
    modal: true,
    width: 390,
    height: 400,
    close: function(){
      $(this).remove();
    }
  });
  
  showLoading();
  
  $.get("", data, function(response){
    hideLoading();
    $("#text-view p").text(response);
    $("#text-view").dialog('open');
  });
}


function showLoading(){
  $("#loading").css("display", "block");
}

function hideLoading(){
  $("#loading").css("display", "none");
}




// @todo: make this data to be loaded dynamically
AnalysisMethods = new Array();
AnalysisMethods[1] = {
  name: "Identical Sentences",
  hasParameters: false,
  parameters: {},
  tip: "This method will look for identical sentences"
}

AnalysisMethods[2] = {
  name: "Ignore short words",
  hasParameters: true,
  parameters: {
    cutSize: 3
  },
  tip: "This method will ignore words of length up to a specified number of letters"
}

function AnalysisMethodsString(){
  var str = "";
  str += "<div class='analysis-method'>";
  str += "<select class='analysis-method-id'>";
  for (m in AnalysisMethods) {
    str += "<option value='" + m + "'>" + AnalysisMethods[m].name + "</option>";
  }
  str += "</select>";
  str += "<div class='analysis-method-parameters' style='display: none;'>";
  str += "</div>";
  str += "</div>";
}

/*
 function AnlaysisMethod(method){
 this.id = method.id;
 this.name = method.name;
 this.tip = method.tip;
 this.hasParameters = method.hasParameters;
 this.parameters = method.parameters;
 }
 AnalysisMethod.prototype.toString = function(){
 var str = "";
 str += "<div class='analysis-method'>";
 str += "<select class='analysis-method-id'>";
 str += "<option value='" + this.id + "'>" + this.name + "</option>";
 str += "</select>";
 str += "</div>";
 }*/
function AnalysisResult(result){
  this.supiciousFileId = result.suspiciousFileId;
  this.plagiarismRatio = result.plagiarismRatio; // number in [0,1]
  this.suspiciousText = result.suspiciousText;
}

AnalysisResult.prototype.valueOf = function(){
  return this.plagiarismRatio;
}

AnalysisResult.prototype.toString = function(){
  var str = "";
  var lastParagraph = this.suspiciousText[0].paragraph;
  
  str += "<p>";
  for (var i = 0; i < this.suspiciousText.length; i++) {
    if (this.suspiciousText[i].paragraph != lastParagraph) {
      str += "</p>";
      str += "<p>";
      lastParagraph = this.suspiciousText[i].paragraph;
    }
    
    str += "<span class=" + this.suspiciousText[i].type + "-sentence>";
    str += this.suspiciousText[i].phrase;
    str += "</span>";
  }
  str += "</p>";
}





function FileDatabaseItem(fileinfo){
  this.id = fileinfo.id;
  this.filename = fileinfo.fileName;
  this.fileType = fileinfo.fileType;
  this.creationTime = fileinfo.creationTime;
  this.analysisResults = null;
}

FileDatabaseItem.prototype.toString = function(){
  var str = "";
  if (fileTypeToTypeString(this.fileType) == "reference") {
  
    str += "<li class='ui-corner-all ui-helper-clearfix' id='reference-file-" + this.id + "'>";
    str += "<p>" + this.filename + "</p>";
    str += "<span class='ui-icon ui-icon-trash remove-file'></span>";
    str += "<span class='ui-icon ui-icon-search view-contents'></span>";
    str += "</li>";
  }
  else 
    if (fileTypeToTypeString(this.fileType) == "suspicious") {
      str += "<tr id='suspicious-file-" + this.id + "'>";
      
      str += "<td class='suspicious-file-name'><p>";
      str += this.filename;
      str += "</p><span class='ui-icon ui-icon-trash remove-file'></span>";
      str += "<span class='ui-icon ui-icon-search view-contents'></span>";
      str += "</td>";
      
      str += "<td class='analysis-method'>";
      str += "  <div class='analysis-method-select-wrapper'>";
      str += "    <select>"
      str += "      <option value='1'>Identical sentences</option>";
      str += "      <option value='2'>Ignore short words</option>";
      str += "    </select>";
      str += "    <div class='analysis-method-parameters ignore-short-words-parameters'>";
      str += "      <p>Cut Length:</p><input type='text' value='3' />";
      str += "    </div>";
      str += "  </div>";
      str += "  <span class='ui-icon ui-icon-help'></span>";
      str += "  <div class='tooltip-wrapper'>";
      str += "    <p class='ui-corner-all'></p>";
      str += "  </div>";
      str += "</td>";
      
      str += "<td class='suspicious-file-go'>";
      str += "  <p class='ui-state-default'>Go!</p>";
      str += "</td>";
      
      /*      str += "<td class='plagiarism-ratio'>";
     str += "  <span class=plagiarism-ratio-progressbar></span>";
     str += "</td>";
     
     str += "<td class='details'>";
     str += "  <p class='ui-state-default'>details</p>";
     str += "</td>";*/
      str += "</tr>";
    }
  return str;
}

FileDatabaseItem.prototype.valueOf = function(){
  return this.id;
}


var fileDatabaseItems = new Array();
fileDatabaseItems["reference"] = new Array();
fileDatabaseItems["suspicious"] = new Array();



function updateFileDatabase(type){
  if (type == undefined) {
    updateFileDatabase("reference");
    updateFileDatabase("suspicious");
    return;
  }
  
  var data = {
    action: "getFileDatabase",
    fileType: type
  };
  
  $.getJSON("", data, function(response){
    recreateFileDatabaseItemsArray(response, type);
    redisplayFileDatabase(type);
  });
}

function recreateFileDatabaseItemsArray(files, type){
  fileDatabaseItems[type].length = 0;
  for (f in files) {
    fileInfo = new FileDatabaseItem(files[f]);
    fileDatabaseItems[type].push(fileInfo);
  }
}

function redisplayFileDatabase(type){
  if ("reference" == type) {
    fileList = "#reference-file-list";
    $(fileList).children("li").fadeOut(100, function(){
      $(this).remove();
    });
    for (f in fileDatabaseItems[type]) {
      $(fileList).append(fileDatabaseItems[type][f].toString());
    }
    $(fileList).children("li").trigger("mouseout");
  }
  else 
    if ("suspicious" == type) {
      fileList = "#suspicious-file-list > tbody";
      $(fileList).children("tr").fadeOut(100, function(){
        $(this).remove();
      });
      for (f in fileDatabaseItems[type]) {
        $(fileList).append(fileDatabaseItems[type][f].toString());
        if (fileDatabaseItems[type][f].analysisResult != null) {
        // @todo: setup progress bar and prepare "details" click event
        }
        else {
        // @todo: setup "waiting" message in progress bar
        }
      }
      
    //      $(fileList).children("tr").trigger("mouseout");
    }
}




$(function(){


  $("#add-text-tab").accordion({
    header: "h3"
  });
  
  new Ajax_upload("#upload-file-reference", {
    action: "cts.php",
    data: {
      action: "uploadFile",
      fileType: "reference"
    },
    name: "userfile",
    onSubmit: function(file, extension){
    },
    onComplete: function(file, response){
      updateFileDatabase("reference");
    }
  });
  
  new Ajax_upload("#upload-file-suspicious", {
    action: "cts.php",
    data: {
      action: "uploadFile",
      fileType: "suspicious"
    },
    name: "userfile",
    onSubmit: function(file, extension){
    },
    onComplete: function(file, response){
      updateFileDatabase("suspicious");
    }
  });
  
  
  
  
  
  
  //  $("#file-management").tabs();
  
  $("#reference-files-content li").live("mouseover", function(){
    $(this).addClass("ui-state-hover-cts");
    $(this).children("span").css("opacity", "1");
  });
  
  $("#reference-files-content li").live("mouseout", function(){
    $(this).removeClass("ui-state-hover-cts");
    $(this).children("span").css("opacity", "0.2");
  });
  
  
  //  $(".suspicious-file-name").live("mouseover", function (){
  //    $(this).addClass("suspicious-file-name-hover");
  //  });
  //
  //  $(".suspicious-file-name").live("mouseout", function (){
  //    $(this).removeClass("suspicious-file-name-hover");
  //  });
  
  
  $(".suspicious-file-go p, .details p").live("mouseover", function(){
    $(this).addClass("ui-state-hover");
  });
  
  $(".suspicious-file-go p, .details p").live("mouseout", function(){
    $(this).removeClass("ui-state-hover");
  });
  
  $(".details p").live("click", function(){
    var row = $(this).parent().parent();
    var rowid = row.attr("id");
    var fileid = rowid.substr(rowid.lastIndexOf("-") + 1);
    $("#detailed-results-file-" + fileid).dialog("open");
  });
  
  $("#analysis-content span.remove-file").live("click", function(){
    var id = $(this).parent().parent().attr("id");
    id = id.substr(id.lastIndexOf("-") + 1);
    removeFile("suspicious", id);
  });
  
  $("#reference-files-content span.remove-file").live("click", function(){
    var id = $(this).parent().attr("id");
    id = id.substr(id.lastIndexOf("-") + 1);
    removeFile("reference", id);
  });
  
  
  $("#analysis-content span.view-contents").live("click", function(){
    var id = $(this).parent().parent().attr("id");
    id = id.substr(id.lastIndexOf("-") + 1);
    viewFileContents("suspicious", id);
  });
  
  $("#reference-files-content span.view-contents").live("click", function(){
    var id = $(this).parent().attr("id");
    id = id.substr(id.lastIndexOf("-") + 1);
    viewFileContents("reference", id);
  });
  
  $(".analysis-method-parameters").hide();
  
  $(".analysis-method-select-wrapper").live("mouseover", function(){
    // @todo: this is hardcoded; should use analysis method information from the webservice!
    if ($("select option:selected", this).val() == 2) {
      $(this).children(".analysis-method-parameters").show();
    }
  });
  
  $(".analysis-method-select-wrapper").live("mouseout", function(){
    $(this).children(".analysis-method-parameters").hide();
  });
  
  $(".analysis-method .ui-icon-help").live("mouseover", function(){
    // @todo: this is hardcoded; should use analysis method information from the webservice!
    var methodWrapper = $(this).siblings(".analysis-method-select-wrapper");
    var method = $("select option:selected", methodWrapper).val();
    var tip = AnalysisMethods[method].tip;
    
    $(this).siblings(".tooltip-wrapper").children("p").text(tip);
    
    $(this).siblings(".tooltip-wrapper").show();
  });
  
  $(".analysis-method .ui-icon-help").live("mouseout", function(){
    $(this).siblings(".tooltip-wrapper").hide();
  });
  
  $(".suspicious-file-go p").live("click", function(){
    //run analysis, show progress bar, prepare results
    var row = $(this).parent().parent();
    var rowid = row.attr("id");
    var fileid = rowid.substr(rowid.lastIndexOf("-") + 1);
    
    var method = $("select option:selected", row).val();
    
    // @todo: hardcoded!
    var methodParams = null;
    if (method == 2) {
      methodParams = $(".ignore-short-words-parameters input", row).val();
    }
    
    
    // show loading...
    showLoading();
    
    // remove ratio progressbar and details button
    row.children(".plagiarism-ratio").remove();
    row.children(".details").remove();
    $("#detailed-results-file-" + fileid).remove();
    
    
    var data = {
      action: "runAnalysis",
      fileId: fileid,
      analysisMethod: method,
      analysisParams: methodParams
    }
    
    // ajax
    $.getJSON("", data, function(response){
      // hide loading...
      hideLoading();
      
      ratio = response.plagiarismRatio * 100;
      
      //create progressbar
      $("<td class='plagiarism-ratio'><span class='plagiarism-ratio-progressbar'></span></td>").appendTo(row);
      $(".plagiarism-ratio-progressbar", row).progressbar({
        value: ratio
      });
      
      
      // create the window with the detailed results
      if (ratio > 0) {
        var text = "";
        var sText = response.suspiciousText;
        var lastParagraph = sText[0].paragraph;
        
        text += "<p>";
        
        for (s in sText) {
          if (lastParagraph != sText[s].paragraph) {
            text += "</p><p>";
            lastParagraph = sText[s].paragraph;
          }
          
          text += "<span class='" + sText[s].type + "'>";
          text += sText[s].phrase + ". ";
          text += "</span>";
        }
        
        text += "</p>";
        
        //        window.alert(text);
        
        var detailedText = $("<div class='detailed-text' id='detailed-results-file-" + fileid + "'>" + text + "</div>");
        detailedText.appendTo("body");
        detailedText.dialog({
          autoOpen: false,
          modal: true,
          width: 390,
          height: 400,
          close: function(){
//            $(this).close();
          }
        });
        $("<td class='details'><p class='ui-state-default'>details</p></td>").appendTo(row);
      }
    });
    
  });
  
  
  
  
  
  
  
  
  
  
  
  //  $(".upload-file-button, .copy-and-paste-button").css("cursor", "default");
  //  $(".upload-file-button, .copy-and-paste-button").addClass("ui-state-default");
  
  //  $(".copy-and-paste-button").add($(".upload-file-button").parent()).css("cursor", "default");
  //  $(".copy-and-paste-button").add($(".upload-file-button").parent()).addClass("ui-state-default");
  $(".copy-and-paste-button").add($(".upload-file-button")).add($(".send-url-button")).css("cursor", "default");
  $(".copy-and-paste-button").add($(".upload-file-button")).add($(".send-url-button")).addClass("ui-state-default");
  
  
  //  $(".upload-file-button, .copy-and-paste-button").hover(function(){
  //  $(".copy-and-paste-button").add($(".upload-file-button").parent()).hover(function(){
  $(".copy-and-paste-button").hover(function(){
    $(this).addClass("ui-state-hover");
  }, function(){
    $(this).removeClass("ui-state-hover");
  });
  
  
  
  $(".copy-and-paste-button").click(function(){
    var type = $(this).attr("id");
    type = type.substr(type.lastIndexOf("-") + 1);
    // setup filename:
    var filename = $("#copy-and-paste-filename").val();
    if (filename == "") {
      filename = type + ".txt";
    }
    
    var contents = $("#copy-and-paste-contents").val();
    if (contents.length == 0) {
      // @todo: show error, empty file
      window.alert("Cannot send empty file.");
      return;
    }
    
    var data = {
      action: "sendText",
      filename: filename,
      fileContents: contents,
      fileType: type
    };
    
    // send the file
    showLoading();
    $.post("#", data, function(response){
      updateFileDatabase(type);
      hideLoading();
    }, "json");
  });
  
  
    $(".send-url-button").click(function(){
    var type = $(this).attr("id");
    type = type.substr(type.lastIndexOf("-") + 1);
    
    var url = $("#send-url-url").val();
    if (url.length == 0) {
      // @todo: show error, empty url
      window.alert("Cannot send empty url.");
      return;
    }
    
    var data = {
      action: "sendUrl",
      url: url,
      fileType: type
    };
    
    // send the file
    showLoading();
    $.post("#", data, function(response){
      updateFileDatabase(type);
      hideLoading();
    }, "json");
  });
  
  
  
  
  $(".plagiarism-ratio-progressbar").progressbar({
    value: 30
  });
  
  
  
  updateFileDatabase();
});
