
/* general display method
  displays the response of another function
  (e.g. an ajax request) in the main display
  area #content
*/
var displayResponse = function(data) {
  $("#content").html(data);
}

var leavingEditorSecure = function() {
	if (confirm ("Ihre Daten wurden noch nicht gespeichert. Möchten Sie den Editor trotzdem verlassen?")){
		changenosave = 0;
		return 1;}
	else {
		return false;}
} 

/* =============== display saved versions of an item ======= */
var displayVersions = function(itemId) {
	$.get("/cgi-bin/tce/listversions.pl?itemid=" + itemId,function(data) {displayResponse(data);});
}

var restoreVersion = function(filename,itemId) {
	if (confirm("Sind Sie sicher, dass Sie diese Version zur aktuellen Version machen möchten?")) {
	$.get("/cgi-bin/tce/listversions.pl?restore=" + filename + "&itemid=" + itemId,function(data){displayResponse(data);});
}}

/* ================== display item metadata ================ */
var displayItemMetadata = function(itemId) {
	$.get("/cgi-bin/tce/metaitem.pl?itemid=" + itemId,function(data) {displayResponse(data);});
}

/* ===================== delete an item ==================== */
var deleteItem = function(itemId) {
	if (confirm("Sind Sie sicher, dass Sie diesen Vorgang löschen möchten?")) {
	$.get("/cgi-bin/tce/deleteitem.pl?itemid=" + itemId,function(data){displayResponse(data);});
}}

/* ===================== export an item ==================== */
var exportItem = function(itemId) {
	exportcurrent = 0;
	$.get("/cgi-bin/tce/exportitem.pl?itemid=" + itemId,function(data) {displayResponse(data);});
}

/* ===================== archive an item ==================== */
var archiveItem = function(itemId) {
	if (((exportcurrent == 0)||(confirm("Der Vorgang wurde seit der letzten Bearbeitung nicht mehr exportiert.")))&&(confirm("Sind Sie sicher, dass Sie diesen Vorgang jetzt archivieren möchten?"))) {
	  var archiveName = prompt("Geben Sie den Namen an, unter dem der Vorgang archiviert werden soll",itemId);
	  $.get("/cgi-bin/tce/archiveitem.pl?itemid=" + itemId + "&filename=" + archiveName,function(data) {displayResponse(data);}); }
}

var listArchivedItems = function() {
	var searchTerm = prompt("Nach einem Vorgangstitel suchen");
	$.get("/cgi-bin/tce/listarchiveditems.pl?search=" + searchTerm,function(data) {displayResponse(data);});
}

var restoreItem = function(itemId) {
	$.get("/cgi-bin/tce/unarchiveitem.pl?itemid=" + itemId,function(data) {displayResponse(data);});
}
/* ===================== create a new item ================= */
var createNewItem = function() {
    if (changenosave == 0 || leavingEditorSecure()) {
    $.get("/cgi-bin/tce/newitem.pl",function(data){displayResponse(data);});
}}



var deleteDownloadFile = function() {
	$.get("/cgi-bin/tce/newitem.pl?action=deleteDownload",function(data){displayResponse(data);});
}

var suggestItemName = function(data) {
	$("#createnewitem1_itemid").val(data);
}


/* ======================= editor ====================== */
var listExistingItems = function() {
  if (changenosave == 0 || leavingEditorSecure()) {
  $.get("/cgi-bin/tce/listitems.pl",function(data){displayResponse(data);});
}}

var startEditor = function(itemId) {
  $.get("/cgi-bin/tce/edititem.pl?itemid=" + itemId,function(data){displayResponse(data);});
}



var addStructElement = function(data,mode) {
  /* create a new structElem object */
  var myElement       = new structElem;
  
  /* store user input from form */
  if (mode == 1)
  {
  myElement.storeMetadata(data.metadata);
  if (isNaN(data.startpage)) {
  myElement.startpage = data.startpage;
  myElement.endpage = data.endpage;
  }
  else { 
  myElement.startpage      = pageArray[data.startpage] || pageArray[0];
  myElement.endpage        = pageArray[data.endpage] || pageArray[0];
  } 
  myElement.id             = data.id; 
  myElement.hierarchyLevel = data.hierarchyLevel;
  }
  else
  {

  myElement.storeMetadata(data.elements["metadata"].value);
  if (data.elements["startpageValue"].value) myElement.startpage = pageArray[data.elements["startpageValue"].value];
  if (data.elements["endpageValue"].value) myElement.endpage   = pageArray[data.elements["endpageValue"].value];
  /* create unique id */
  /* myElement.id        = structIdPrefix + "_" + structCounter++; */
  myElement.id = getStructElementId();
  }

  
  /* add to array of structElem objects */
  structArray.push(myElement);
  
  /* set new structMaxLevel if necessary */
  if (myElement.hierarchyLevel > structMaxLevel) structMaxLevel = myElement.hierarchyLevel;
  
  /* clear the form */
  if (mode != 1)
  {
  data.reset();
  $("#formMetadata").focus();
  $("#formForm").attr("onsubmit","addStructElement(this)");
  }
  /* refresh the tree of struct elements */
  displayStructTree(1);
  changenosave = 1;
  
  return 1;
}

var getStructElementId = function() {
	var newId = structIdPrefix + "_" + structCounter++;
	for (var i = 0; i < structArray.length; i++) {
		if (structArray[i].id == newId) {
			newId = structIdPrefix + "_" + structCounter++;}}
	return newId;
}

var updateStructElement = function(data,id) {

  
  /* store user input from form */
  structArray[id].storeMetadata(data.elements["metadata"].value);
  structArray[id].startpage = pageArray[data.elements["startpageValue"].value];
  structArray[id].endpage   = pageArray[data.elements["endpageValue"].value];

  /* set new structMaxLevel if necessary */
  if (structArray[id].hierarchyLevel > structMaxLevel) structMaxLevel = structArray[id].hierarchyLevel;

  /* clear the form */
  data.reset();
  $("#formMetadata").focus();
  $("#formForm").attr("onsubmit","addStructElement(this)");
  $("#formEndpageValue").val(0);
  $("#formStartpageValue").val(0);
  
  /* refresh the tree of struct elements */
  changenosave = 1;
  displayStructTree(0);      
}



var editStructElement = function(data) {
  /* writes the data stored in a structElem object
    back into the editing form
  */
  
  /* highlights the currently edited structtreeitem */
  $("#s" + currentStructTreeItem).removeClass("sti_highlight");
  currentStructTreeItem = data;
  $("#s" + data).addClass("sti_highlight");
  
  displayImage(structArray[data].startpage.order);
  $("#formEndpageValue").val(0);
  $("#formStartpageValue").val(0);
  
  var picarecord = structArray[data].metadata.split("\n");
      picarecord.sort();
      
  $("#formMetadata").val(picarecord.join("\n"));
  $("#formStartpage").val(pageSelect[structArray[data].startpage.order].label);
  $("#formStartpageValue").val(structArray[data].startpage.order);
  $("#formEndpage").val(pageSelect[structArray[data].endpage.order].label);
  $("#formEndpageValue").val(structArray[data].endpage.order);
  $("#formForm").attr("onsubmit","updateStructElement(this," + data + ")");
  $("#formMetadata").focus();
  
  changenosave = 1;
}



var deleteStructElement = function(data) {
  /* deletes a structElem object from structArray
    after deletion the struct elements tree must be rebuild
  */
  if (confirm("Sind Sie sicher, dass Sie dieses Element löschen möchten?")) {
  	structArray.splice(data,1);
  	displayStructTree(0);
  }
  changenosave = 1;
}



var levelUpStructElement = function(data) {
  structArray[data].levelUp();
  
  /* set new structMaxLevel if necessary */
  if (structArray[data].hierarchyLevel > structMaxLevel) structMaxLevel = structArray[data].hierarchyLevel;
  
  changenosave = 1;
  displayStructTree(0);
}



var levelDownStructElement = function(data) {
  structArray[data].levelDown();
  changenosave = 1;
  displayStructTree(0);
}    

var removeHierarchy = function() {
   for (var i = 0; i < structArray.length; i++)	{
   	structArray[i].hierarchyLevel = 0;
   }
   changenosave = 1;
   structMaxLevel = 0;
   displayStructTree(0);
}

var displayStructTree = function(data) {

    ungroup();
    $("#displayAreaStructTree").html("");
    for (var i = 0; i < structArray.length; i++) {
      $("#displayAreaStructTree").append(makeStructListEntry(i));
    }
    clearInputForm();
}
  



var makeStructListEntry = function(data)  {
  /* creates a div representing an entry in the tree of stuct elements
    called in displayStructTree() only.
  */
  var newElementEntry  = "<div class='structtreeitem' id='s"+ data + "' ondblclick='markForGrouping(\"s"+ data +"\")'>";
      newElementEntry += "<span class='sti_icons'>";
      newElementEntry += "<a href='javascript:void(0)' onclick='levelUpStructElement(" + data + ")' title='Eine Ebene h&ouml;her stufen'><img src='/tce/include/images/back_alt.png' alt='HÃ¶her' width='16' height='16'/></a>";
      newElementEntry += "&nbsp;"; 
      newElementEntry += "<a href='javascript:void(0)' onclick='levelDownStructElement(" + data + ")' title='Eine Ebene niedriger stufen'><img src='/tce/include/images/forward_alt.png' alt='Tiefer' width='16' height='16'/></a>";
      newElementEntry += "&nbsp;";  
      newElementEntry += "<a href='javascript:void(0)' onclick='editStructElement(" + data + ")' title='Bearbeiten'><img src='/tce/include/images/edit.png' alt='Bearbeiten' width='16' height='16'/></a>";
      newElementEntry += "&nbsp;";
      newElementEntry += "<a href='javascript:void(0)' onclick='deleteStructElement(" + data + ")' title='L&ouml;schen'><img src='/tce/include/images/trash.png' alt='LÃ¶schen' width='16' height='16'/></a>";
      newElementEntry += "</span>";
      newElementEntry += "<span class='sti_title'>";
      newElementEntry += "&nbsp;"; 
      for (var i = structArray[data].hierarchyLevel; i < structMaxLevel; i++) {
        newElementEntry += "&raquo; ";
      }                     
      newElementEntry += structArray[data].shorttitle();
      newElementEntry += "</span>";
      newElementEntry += "&nbsp;<span class='sti_pages'>";
      if (structArray[data].startpage.label) newElementEntry += structArray[data].startpage.label;
      newElementEntry += "-";
      if (structArray[data].endpage.label) newElementEntry += structArray[data].endpage.label;
      newElementEntry += "</span>";
      newElementEntry += "&nbsp;<span class='sti_images'>(";/***********************/
      if (structArray[data].startpage.order) newElementEntry += structArray[data].startpage.order;
      newElementEntry += "-";
      if (structArray[data].endpage.order) newElementEntry += structArray[data].endpage.order;
      newElementEntry += ")</span>";      
      newElementEntry += "</div>";      
      return newElementEntry;
}


/* 
==================================================================================================================
                               Initialisierung des Editors
==================================================================================================================                               
*/
                              
var initEditor = function(){
  /* initiate pageArray */
  $("#displayAreaStructTree").html("Einlesen der Bilddateien...");
  $.getJSON("/cgi-bin/tce/getdata.pl?get=pages&itemid=" + itemId,function(data) { 
    pageArray = data; 
    pageArray.unshift({order: 0, label: 'undefiniert', structId: null});
    for (var i = 0; i < pageArray.length; i++) {
      var term = {label: '', value: 0}; 
      if (!pageArray[i].label) {term.label += "ungez.";} 
      else {term.label += pageArray[i].label;} 
      term.label += " (" + pageArray[i].order + ")"; 
      term.value = pageArray[i].order;
      pageSelect.push(term);
    }
    /* initiate structArray */
    $("#displayAreaStructTree").html("Einlesen des Strukturbaums...");
    $.getJSON("/cgi-bin/tce/getdata.pl?get=struct&itemid=" + itemId,function(data){
      for (var i = 0;i < data.length; i++) {
        addStructElement(data[i],1);        
      };
      structCounter = structArray.length +1; 
      /* set autocomplete */
      $("#formStartpage").autocomplete({
        source: pageSelect, 
        delay: 0, 
        focus: function(event,ui) {
          $("#formStartpage").val(ui.item.label);
          return false;
        }, 
        select: function(event,ui){
          $("#formStartpage").val(ui.item.label); 
          $("#formStartpageValue").val(ui.item.value);
          displayImage(ui.item.value);
          return false;
        }}); 
      $("#formEndpage").autocomplete({
        source: pageSelect, 
        delay: 0, 
        focus: function(event,ui){
          $("#formEndpage").val(ui.item.label);
          return false;
          }, 
        select: function(event,ui){
          $("#formEndpage").val(ui.item.label);
          $("#formEndpageValue").val(ui.item.value);
          displayImage(ui.item.value);
          return false; 
          }});
        /* change headline */
        $("#headlineeditor").html("Vorgang " + itemId + " bearbeiten");
        /* create draggable */
        $("#editorinputwidget").draggable();
        $("#functionswidget").draggable();
        /* create sortable */
        $("#displayAreaStructTree").sortable({
          update: function(event,ui) {
            var ser = $("#displayAreaStructTree").sortable("toArray");
            var tmpArray = new Array;
            for (var i = 0; i < ser.length; i++) {
              var serIndex = eval(ser[i].substr(1));
              tmpArray.push(structArray[serIndex]);
            }
            structArray = new Array;
            structArray = tmpArray;
            displayStructTree(0);
          }});});});   
}

/*
==============================================================================================================
                                       Anzeige der Images
==============================================================================================================
*/
                                       
var initImageDisplay = function() {
	$.getJSON("/cgi-bin/tce/getdata.pl?get=images&itemid=" + itemId,function(data){
		imageArray = new Array;
		imageArray = data;
		currentImage = 1;
		displayImage(currentImage);
		
});}

var displayImage = function(data) {
	if (isNaN(data)) {
		alert("Bitte die (physische) Imagenummer eingeben");
	}
	else {
		
		if ((data < imageArray.length) && (data > -1)) {
			$("#editorimagedisplay").attr("src",imageArray[data]);
			currentImage = data;
			$("#editorcurrentimage").val(data);
		}
		else {
			alert("Das von Ihnen ausgewählte Image (" + data + ") existiert nicht");
		}
	}
}

var displayPreviousImage = function(data) {
	displayImage(currentImage - data);
}

var displayNextImage = function(data) {
	displayImage(parseInt(currentImage) + parseInt(data));
}

var displayFirstImage = function() {
	displayImage(1);
}

var displayLastImage = function() {
	displayImage(imageArray.length - 1);
}

var displayInputWidget = function() {
	$("#editorinputwidget").toggle("blind");
	$("#editorinputwidgetcontrol").toggle("blind");
}

var displayFunctionsWidget = function() {
	$("#functionswidget").toggle("blind");
	$("#functionswidgetcontrol").toggle("blind");
}

/*
======================================================================================================================
                                        Gruppieren von Strukturelementen
======================================================================================================================                                  
*/

var markForGrouping = function(data) {
	
	if ($("#"+ data).hasClass('groupedItem')) {
		$("#"+ data).removeClass('groupedItem');
		groupedItems = groupedItems - 1;
		$("#group").after($("#"+ data));
		if (groupedItems == 0) {
			$("#group").remove();
		}
	}
	else {
		if (groupedItems == 0) {
			$("#"+ data).before("<div id='group' class='group_container'><div class='group_navigation' id='grpnav'><span onclick='groupRelease()'>Gruppierung aufheben [x]</span></div></div>");
		}		
		$("#"+ data).addClass('groupedItem');
		groupedItems = groupedItems + 1;
		$("#"+ data).appendTo("#group");
	}
}

var groupRelease = function() {
            ungroup();
            var ser = $("#displayAreaStructTree").sortable("toArray");
            var tmpArray = new Array;
            for (var i = 0; i < ser.length; i++) {
              var serIndex = eval(ser[i].substr(1));
              tmpArray.push(structArray[serIndex]);
            }
            structArray = new Array;
            structArray = tmpArray;
            displayStructTree(0);
}

var ungroup = function() {
	$("#group > div.structtreeitem").unwrap();
	$(".groupedItem").removeClass('groupedItem');
	$("#grpnav").remove();
	$("#group").remove();
	groupedItems = 0;
}

/*
======================================================================================================================
                                  Funktionen beim Speichern und Verlassen des Editors
======================================================================================================================
*/
                                  
var addEndPages = function() {
  var pageDistance = prompt("Bitte geben Sie den Abstand zwischen 2 Strukturelementen in Seiten an: \n 0 : Das nächste Strukturelement beginnt auf der Seite auf der das vorhergehende endet. \n 1 : Das nächste Strukturelement beginnt immer auf einer neuen Seite. \n 2 : Zwischen zwei Strukturelementen befindet sich immer eine leere Seite usw.",0);
  for (var i = 0; i < structArray.length; i++) {
    if (structArray[i].endpage.order == 0) {
      var hLevel = structArray[i].hierarchyLevel;
      var newEndpage = pageArray[pageArray.length - 1];
      for (var ii = i + 1; ii < structArray.length; ii++) {
          if ((structArray[ii].hierarchyLevel >= hLevel) && (structArray[ii].startpage.order > 0)) {
            newEndpage = pageArray[structArray[ii].startpage.order - pageDistance];
            break;
          }}
      structArray[i].endpage = newEndpage;
      displayStructTree(0);
    }}
}

var saveStructTree = function() {
  
  ungroup();
  var structTree = JSON.stringify(structArray);
  var param = {
    data: structTree,
    itemid: itemId
  };
  $.post("/cgi-bin/tce/saveitem.pl",param,function(data){
    changenosave = 0;
    exportcurrent = 1;
    var response = eval(data);
    alert(response.message);
  });
}

var clearInputForm = function() {
  $("#s" + currentStructTreeItem).removeClass("sti_highlight");
  $("#formMetadata").focus();
  $("#formMetadata").val('');
  $("#formForm").attr("onsubmit","addStructElement(this)");
  $("#formEndpageValue").val(0);
  $("#formStartpageValue").val(0);
  $("#formEndpage").val('');
  $("#formStartpage").val('');
}

var closeEditor = function() {
  changenosave = 0;
  addEndPages();
  saveStructTree();
  listExistingItems();
}