rectID = 0;
colors = ["#edd400","#73d216","#cc0000","#f57900","#3465a4","#c17d11","#75507b","#fce94f","#8ae234","#ef2929","#fcaf3e","#729fcf","#eeeeec","#e9b96e","#ad7fa8","#888a85","#c4a000","#4e9a06","#a40000","#ce5c00","#204a87","#babdb6","#8f5902","#5c3566","#2e3436"].map(i => i + "70"); //Tango Colors with opacity
function addRectangle(){
addRectangle1("", 0,0,1000,100)
}
function scalefactor(){
return $('#sliceImg').innerWidth() / $('#sliceImg').prop('naturalWidth');
}
function refitRect(id){
$('#Rect' + id).css('transform', 'scale(' + scalefactor() + ')');
}
function resizeAllRect() {
console.log("resizing");
for (var i = 0; i < rectID; i++) {
refitRect(i);
$('#Rect' + i).css("top", $('#Rect' + i).attr("y") * scalefactor() + "px");
$('#Rect' + i).css("left", $('#Rect' + i).attr("x") * scalefactor() + "px");
}
}
function changeRectPosition(id, style, amount){
$('#Rect' + id).css(style, amount + "px");
refitRect(id);
}
function addRectangle1(id,x,y,w,h,pattern,idtext,assignmentsstation,assignments){
//Show input fields
var clone = document.importNode(document.querySelector('#RectanglesSetup').content,true);
var localID = rectID
if(id != "")
localID = id;
$('[data-class=RectID]',clone).text("" + localID);
$('[data-class=mainDiv]',clone).hover(function(){
$('#Rect' + localID).css("background", colors[localID % colors.length]);
$('#FormRect' + localID).css("background", colors[localID % colors.length]);
},
function(){
$('#Rect' + localID).css("background", "none");
$('#FormRect' + localID).css("background", "none");
});
$('[data-class=mainDiv]',clone).attr('id', 'FormRect' + localID);
$('[data-class=x]',clone).val(x);
$('[data-class=x]',clone).on('input', function(e) {
changeRectPosition(localID, "left", this.value * scalefactor() );
});
$('[data-class=y',clone).val(y);
$('[data-class=y]',clone).on('input', function(e) {
changeRectPosition(localID, "top", this.value * scalefactor());
});
$('[data-class=w',clone).val(w);
$('[data-class=w]',clone).on('input', function(e) {
changeRectPosition(localID, "width", this.value );
});
$('[data-class=h',clone).val(h);
$('[data-class=h]',clone).on('input', function(e) {
changeRectPosition(localID, "height", this.value );
});
//allow to disable rectangle
$('[data-class=setinactive]',clone).change(function() {
$(this).parent().parent().parent().toggleClass("singleRect");
});
$('[data-class=removeRect]',clone).on('click', function(e) {
$(this).parent().parent().parent().remove();
});
//Alle Abkürzungen einfügen und prüfen ob im pattern angegeben
abk.forEach(function(item){
var clonepattern = document.importNode(document.querySelector('#RectanglePattern').content,true);
$('[data-class=abk]',clonepattern).text(item);
$('[data-class=input]',clonepattern).prop('name', item);
if(typeof pattern !== 'undefined' && pattern[item]){
$('[data-class=input]',clonepattern).prop('checked', true);
}
$('[data-class=input]',clonepattern).change(refreshassignments);
$('[data-class=RectanglePattern',clone).append(clonepattern);
});
var clonepatternidtext = document.importNode(document.querySelector('#RectanglePatternText').content,true);
if(typeof idtext !== 'undefined'){
$('[data-class=input]',clonepatternidtext).val(idtext);
}
$('[data-class=RectanglePattern',clone).append(clonepatternidtext);
//add Assignment Station
var clonepattern = document.importNode(document.querySelector('#RectanglesAssignment').content,true);
$('[data-class=Assignment]',clonepattern).attr("name", "Station");
$('[data-class=AssignmentAbk]',clonepattern).text("Station");
//Stationen einfügen
$.ajax({
type: "GET",
url: "../server/",
dataType: "xml",
success: function(xml) {
$(xml).find('station').each(function(index){
//console.log($(this).attr('id'));
$('[data-class=AssignmentOptionen]',clonepattern).append('');
});
},
async: false
});
//station hinzufügen/löschen
$('[data-class=AssignmentAdd]',clonepattern).on('click', function(e) {
var clonepatternvalue = document.importNode(document.querySelector('#RectanglesAssignmentValue').content,true);
$('[data-class=AssignmentText]',clonepatternvalue).text(e.target.previousElementSibling.value);
//löschen
$('[data-class=AssignmentDelete]',clonepatternvalue).on('click', function(e) {
e.target.parentNode.remove();
});
e.target.nextElementSibling.append(clonepatternvalue)
});
//Station Ausfüllen
if(typeof assignmentsstation !== 'undefined' && assignmentsstation){
$.each(assignmentsstation, function(i, item){
var clonepatternvalue = document.importNode(document.querySelector('#RectanglesAssignmentValue').content,true);
$('[data-class=AssignmentText]',clonepatternvalue).text(item);
//löschen
$('[data-class=AssignmentDelete]',clonepatternvalue).on('click', function(e) {
e.target.parentNode.remove();
});
$('[data-class=AllAssignments]',clonepattern).append(clonepatternvalue)
});
}
$('[data-class=RectangleAssignmentStation]',clone).append(clonepattern);
//add assignments
$.each( fullpattern["pattern"], function(i, item){
var clonepattern = document.importNode(document.querySelector('#RectanglesAssignment').content,true);
$('[data-class=Assignment]',clonepattern).attr("name", item["abk"]);
$('[data-class=AssignmentAbk]',clonepattern).text(item["abk"]);
$.each( item["types"], function(i, item){
if(item != "")
$('[data-class=AssignmentOptionen]',clonepattern).append('');
});
//einfügen
$('[data-class=AssignmentAdd]',clonepattern).on('click', function(e) {
var clonepatternvalue = document.importNode(document.querySelector('#RectanglesAssignmentValue').content,true);
$('[data-class=AssignmentText]',clonepatternvalue).text(e.target.previousElementSibling.value);
//löschen
$('[data-class=AssignmentDelete]',clonepatternvalue).on('click', function(e) {
e.target.parentNode.remove();
});
e.target.nextElementSibling.append(clonepatternvalue)
});
//Default Assignment nur bei angekreuzten pattern ausfüllen
if(typeof pattern !== 'undefined' && pattern[item["abk"]]){
$('[data-class=AssignmentDefaultValue]',clonepattern).text($("#FormPattern2_Form_" + item["abk"]).find(":selected").text());
}
//Assignment Ausfüllen
if(typeof assignments !== 'undefined' && assignments[item["abk"]]){
$.each(assignments[item["abk"]], function(i, item){
var clonepatternvalue = document.importNode(document.querySelector('#RectanglesAssignmentValue').content,true);
$('[data-class=AssignmentText]',clonepatternvalue).text(item);
//löschen
$('[data-class=AssignmentDelete]',clonepatternvalue).on('click', function(e) {
e.target.parentNode.remove();
});
$('[data-class=AllAssignments]',clonepattern).append(clonepatternvalue)
});
}
$('[data-class=RectangleAssignment]',clone).append(clonepattern);
});
$('#imgRectangles').append(clone);
//add rectangle to image
var clone = document.importNode(document.querySelector('#RectanglesImage').content,true);
$('[data-class=RectID]',clone).attr("id","Rect" + localID);
$('[data-class=RectID]',clone).attr("y",y);
//Write text into img. such that this text shall equal the text on the slides
var recttext = "";
abk.forEach(function(item){
if(typeof pattern !== 'undefined' && pattern[item]){
recttext += item;
}
});
if(typeof idtext !== 'undefined' && idtext != ""){
recttext += "ID:" + idtext;
}
$('[data-class=RectID]',clone).text(recttext);
$('[data-class=RectID]',clone).css("top", y * scalefactor() + "px");
$('[data-class=RectID]',clone).css("left", x * scalefactor() + "px");
$('[data-class=RectID]',clone).css("width", w + "px");
$('[data-class=RectID]',clone).css("height", h + "px");
$('[data-class=RectID]',clone).hover(function(){
$('#FormRect' + localID).css("background", colors[localID % colors.length]);
$('#Rect' + localID).css("background", colors[localID % colors.length]);
$('#detailcolumn2').scrollTop( 0 );
$('#detailcolumn2').scrollTop($('#FormRect' + localID).position().top - 50 );
},
function(){
$("#detailcolumn2").stop();
$('#FormRect' + localID).css("background", "none");
$('#Rect' + localID).css("background", "none");
});
$('#imgrect').append(clone);
refitRect(localID);
++rectID;
new Sortable(document.getElementById('imgRectangles'),{
handle: '.handle3',
animation: 150
});
}
function updateSlicerPatternForm(){
}
function createRectForm(station){
var imgsrc = $("#sliceImg").attr("src")
rectID = 0;
$('#imgRectangles').text("");
$('#imgrect').html('');
$.getJSON( "../server/json/Rectangle.json", function( data ) {
$.each( data["Configs"], function(i, item){
if(item["name"] == station){
$.each( item["rects"], function(i, item){
addRectangle1(item["id"],item["X"],item["Y"],item["W"],item["H"],item["pattern"],item["idtext"],item["assignmentsstation"], item["assignments"]);
});
}
});
});
}
function loadStationsForm(){
$.getJSON( "../server/json/Rectangle.json", function( data ) {
$.each( data["Configs"], function(i, item){
$("#loadconfig").append('');
});
$("#loadconfig").on('change', function() {
createRectForm(this.value);
});
});
}
function createJson(){
rects = []
$(".singleRect").each(function() {
var pats = {}
$(this).find(".patternPart3").each(function() {
$(this).find('.patternPart3Input:checked').each(function() {
pats[$(this).attr('name')] = true;
});
});
var txt;
$(this).find(".patternPart3Text").each(function() {
txt = $(this).children("input").val();
});
//get All stations
var assignmentstation = assignmentGetAllStatios($(this));
//get all assignments of current Rectangle
var assignments = assignmentGetAllAssignments($(this));
rect = {id: $( this ).find(".RectID").text(), X:$( this ).find('input[data-class="x"]').val(), Y:$( this ).find('input[data-class="y"]').val(), W:$( this ).find('input[data-class="w"]').val(), H:$( this ).find('input[data-class="h"]').val(), pattern: pats, idtext: txt, assignmentsstation: assignmentstation, assignments: assignments};
rects.push(rect);
});
allrects = {name: $("#loadconfig").val(), rects: rects};
return allrects;
}
function createJsonCutting(){
var rects = createJson();
rects.rects.forEach(function(value) {
pattern = value.pattern;
abk.forEach(function(item){
if(typeof $("#FormPattern2_Form_" + item).val() !== 'undefined' && typeof $("#FormPattern2_Form_" + item).val() !== 'undefined'){
if(pattern[item]){
//if rectangle is checked but nothing has been selected
if($("#FormPattern2_Form_" + item).find(":selected").text() == ""){
pattern[item] = "NoSelection";
}
else{
pattern[item] = $("#FormPattern2_Form_" + item).find(":selected").text();
}
}
}
});
});
return rects;
}
function recCombi(data, currindex, result, cur) {
var Keys = Object.keys(data);
var optionKey = Keys[currindex];
var vals = data[optionKey];
for (var i = 0; i < vals.length; i++) {
cur[optionKey] = vals[i];
if (currindex + 1 < Keys.length) {
recCombi(data, currindex + 1, result, cur);
}
else {
var res = JSON.parse(JSON.stringify(cur));
result.push(res);
}
}
return result;
}
//gets assignment station for current rectangle
function assignmentGetAllStatios(cur) {
var assignmentstation = []
cur.find(".RectangleAssignmentStation div").each(function() {
var allass = new Set();
$(this).find(".RectanglesAssignmentValue").each(function() {
allass.add($(this).text());
});
if(allass.size)
assignmentstation = Array.from(allass);
});
return assignmentstation;
}
//gets assignments for current rectangle
function assignmentGetAllAssignments(cur, addDefaultValues = false) {
var assignments = {};
cur.find(".RectangleAssignment div").each(function() {
assname = $(this).attr('name')
var allass = new Set();
if(addDefaultValues && $(this).find(".RectanglesAssignmentDefaultValue").first().text() != ""){
allass.add($(this).find(".RectanglesAssignmentDefaultValue").first().text());
}
$(this).find(".RectanglesAssignmentValue").each(function() {
allass.add($(this).text());
});
if(allass.size){
assignments[assname] = Array.from(allass);
}
});
return assignments;
}
function assignmentGetAllEmptyAssignments(cur){
var assignments = {};
cur.find(".RectangleAssignment div").each(function() {
assname = $(this).attr('name')
var allass = new Set();
if($(this).find(".RectanglesAssignmentDefaultValue").first().text() != ""){
allass.add($(this).find(".RectanglesAssignmentDefaultValue").first().text());
}
$(this).find(".RectanglesAssignmentValue").each(function() {
allass.add($(this).text());
});
if(!allass.size){
assignments[assname] = "";
}
});
return assignments;
}
function submitSlices(skip = false){
//createJsonCutting();
//check if selected options are also selected in drop down menus
var skippall = false;
if(!skip){
var checkedoptions = new Set();
$("#imgRectangles wasRight input[type=checkbox]:checked").each(function(index, data){
checkedoptions.add($(data).attr("name"))
});
var allskips = [];
checkedoptions.forEach(function(item){
if($("#FormPattern2_Form_" + item).find(":selected").text() == ""){
allskips.push(item);
}
});
if (Array.isArray(allskips) && allskips.length) {
if(!confirm("Achtung: [" + allskips + "] nicht ausgefüllt, fortfahren?")){
skippall = true;
}
}
}
if(!skippall){
request = $.ajax({
type: "POST",
url: "imageSlicer.php",
async: false,
data: { url: $("#sliceImg").attr("src"), savelocation: $("#savelocation").val(), alldata: JSON.stringify(createJsonCutting()) },
success: function(data){
if (!data.hasOwnProperty('override')) {
//clearFormFull();
if(!skip){
alert("Saved Images");
}
}
else if(data.hasOwnProperty('error')){
alert("Achtung Fehler: \n" + data.error)
console.log(data);
}
else{
if(!skip){
overlayOnDupliImages(data.override);
}
}
//Create Assignments (first returned url == first rectangle)
if(data.hasOwnProperty('url')){
var counter = 0;
$(".singleRect").each(function() {
var txt = "";
$(this).find(".patternPart3Text").each(function() {
txt = $(this).children("input").val();
});
//get All stations
var assignmentstation = assignmentGetAllStatios($(this));
//get all assignments of current Rectangle
var assignments = assignmentGetAllAssignments($(this), true);
//in case no assignments are found do next rect
//console.log(assignments);
if(Object.keys(assignments).length === 0){
++counter;
return true;
}
//get all empty assignments of current Rectangle
var emptyassignments = assignmentGetAllEmptyAssignments($(this));
//get all combinations of assignments
var result = recCombi(assignments, 0, [], {});
//Save assignments
//console.log("Save Assignemnts")
$.each(assignmentstation, function(i, station) {
$.each(result, function(i, item) {
//console.log("saving " + i);
var obj = new Object();
obj.img = data.url[counter];
obj.station = station;
$.extend( item, emptyassignments );
obj.parts = item;
obj.assignmentText = txt;
//console.log(obj);
$("#cuttingProgress").text("Saving: " + JSON.stringify(obj))
//use storage function from assignment.js
submitAssignment(obj);
});
});
++counter;
});
}
},
error: function(xhr, status, error){
console.error(xhr);
}
});
}
}
function overlayOnDupliImages(data) {
document.getElementById("overlayNotClickable").style.display = "block";
var clone = document.importNode(document.querySelector('#SlicerDupliOverlay').content,true);
$.each( data, function(i, item){
var clone2 = document.importNode(document.querySelector('#SlicerDupliImageRow').content,true);
$('[data-class=oldimg]',clone2).attr("src", item["old"] + '?rand=' + Math.random());
$('[data-class=newimg]',clone2).attr("src", item["new"] + '?rand=' + Math.random());
$('[data-class=changebutton]',clone2).attr("onclick", "javascript:changeimg(\"" + item["old"] + "\", \"" + item["new"] +"\", this )");
$('[data-class=ImgList]',clone).append(clone2);
});
$('#overlaycontentsizeNotClickable').append(clone)
}
function changeimg(oldimg, newimg, buttonelement) {
$.get( "imageOverride.php?overridden=" + oldimg + "&new=" + newimg , function( data ) {
//hide button
$(buttonelement).hide(200);
});
}
function showJson(){
copy2Clipboard(JSON.stringify(createJson()))
}
function overrideRect(){
if (confirm('Please be carefull when overriding, are you sure?')) {
var curjson = createJson();
$.getJSON( "../server/json/Rectangle.json", function( data ) {
//Override Rects
$.each(data.Configs, function(i, item) {
if(curjson.name == item.name){
//data.Configs[i].rects = curjson.rects;
item.rects = curjson.rects;
console.log("Overriding")
}
});
submitJson("Rectangle.json", JSON.stringify(data));
});
}
}
function copy2Clipboard(datalink) {
const el = document.createElement('textarea');
el.value = datalink;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
function clearFormFull(){
clearForm();
$('#slicerpatterninput').val("");
}
function clearForm(){
$('#FormPattern2').find("select").prop("selectedIndex",0);
}
function fillFormName(value){
$("#slicerpatterninput").val(value);
fillslicerpattern();
}
function fillpatternForm(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
fillslicerpattern();
}
};
function fillslicerpattern(){
clearForm();
jQuery.ajax({
url: "TransformProductCode.php?ProductCode=" + $("#slicerpatterninput").val(),
success: function (data) {
$.each( data, function(i, item){
$("#FormPattern2_Form_" + i).val(item);
});
},
async: false
});
}
function getAllFolders(folder = ""){ //Get DB 2 HTML //has to be synchronus in order to update before loading the rest
$('#selectfolders').find('option').remove()
$('#selectfolders').append("")
$.ajax({
type: "GET",
url: urlUniversalStorage + "server/allfolders/" + folder,
async: false,
dataType: "json",
success: function(data) {
$.each( data, function( key, value ) {
$('#selectfolders').append("")
});
}
});
}
function getAllFiles(folder = ""){ //Get DB 2 HTML //has to be synchronus in order to update before loading the rest
$.ajax({
type: "GET",
url: urlUniversalStorage + "server/images/" + folder,
dataType: "json",
success: function(data) {
$.each( data, function( key, value ) {
console.log(value);
console.log(urlUniversalStorage + "storage/" + folder + "/" + value);
$("#sliceImg").attr("src", urlUniversalStorage + "storage/" + folder + "/" + value)
fillFormName(value);
refreshassignments();
submitSlices(true);
/*
$("#slicerpatterninput").val(value);
fillslicerpattern();
*/
});
}
});
}
function togglenext(currelement){
currelement.next().slideToggle();
}
function refreshassignments(){
console.log("Refreshing")
$(".singleRect").each(function() {
var main = $(this);
$(this).find(".RectangleAssignment div").each(function() {
var curabk = $(this).attr('name');
var next = false;
main.find(".patternPart3 .patternPart3Input:checked ").each(function() {
if($(this).attr('name') == curabk){
next = true;
}
});
if(next){
$(this).find(".RectanglesAssignmentDefaultValue").first().text($("#FormPattern2_Form_" + curabk).find(":selected").text())
}
else{
$(this).find(".RectanglesAssignmentDefaultValue").first().text("")
}
});
});
}
$(document).ready(function() {
createPatternForm();
updateSlicerPatternForm();
loadStationsForm();
getAllFolders();
//press enter to fill out patternform
$("#slicerpatterninput").bind("keypress", {}, fillpatternForm);
/*
$("#sliceImg").bind('load', function() {
resizeAllRect();
});*/
/*
$("#sliceImg").on('load', function () {
resizeAllRect();
});
*/
/*
$('#sliceImg').on('load',function(){
resizeAllRect();
});
*/
$.getJSON( "../server/json/SlicerConfig.json", function( data ) {
if(!data["SlicerRectForm"]){
$("#addRectanglesGroup").hide();
$("#imgRectangles").hide();
$("#Json2ClipboardGroup").hide();
}
});
$(document).on('submit', '#sliceform', function() { //prevent page reload on form submit
return false;
});
$("#showJson").click(function() {
showJson();
});
$("#overrideRect").click(function() {
overrideRect();
});
$("#multiCut").click(function() {
getAllFiles($('#selectfolders').val());
});
$('#pattern2').text("");
var clone = document.importNode(document.querySelector('#patternClone').content,true);
$('[data-class=part]',clone).limitkeypress({rexp: keypressRegex()});
$("#pattern2").append(clone);
//handle zoom event in order to fix rectangle position
window.addEventListener("resize", resizeAllRect, false);
});