var openCardOnStart = false;
var openCardAction = 'edit';
var useTabulator = false;
var show_document_cue = "";
jQuery(document).ready(function() {
	move_toolbar();
});

	
function move_toolbar() {
	if(jQuery('#mainContent ul.toolbar_menu').length == 0) {
		return;
	}
	
	jQuery('#mainContent ul.toolbar_menu').insertBefore(jQuery('#mainContent'));
	jQuery('#menu, #content_full').addClass("menu_opened");
}

//linklist functions
var dc = {};
dc.overlay_mode = false; // Karte offen ja nein
dc.linklist_marked = null; // markierte Zeile in einer linkiste
dc.mouse_in_linklist = false; // wenn der mauszeiger sich ueber einer linkliste befindet, dann true
dc.current_linklist = null; // aktuelle linkliste - entweder direkt im content oder im overlay
dc.current_formname = null;
dc.files;
dc.reorder_call = null; // ajax request zum aendern der reihenfolge in den linklisten

// IC - AM - HD365 ---
dc.serial_no = null;
dc.document_no = null;
dc.document_type = null;
dc.ticket_no_b64 = null;
// IC - AM - HD365 +++

// Grab the files and set them to our variable
function prepareUpload(event) {
	dc.files = event.target.files;
}

function centerElement(_el) {
	_el.css({
        position:'absolute',
        left: ($(window).width() - _el.outerWidth())/2,
        top: ($(window).height() - _el.outerHeight())/4
    });
}

function setFormname(_formname) {
	dc.current_formname = _formname;
}

function setInputId(_input_id) {
	dc.current_input_id = _input_id;
}

function setCurrentToolbarClicked(_el) {
	setFormname(jQuery(_el).data('formname'));
}

function initLinklist() {
	
	dc.linklist_marked = null;
	dc.mouse_in_linklist = false;
	
	jQuery('.linklist').each(function() {
		if(jQuery(this).data('linklist_init') === true) return;
		var thiz = this;
		
		if($(this).hasClass("sortableTable")) {
			makeSortable($(this));
		}
		
		jQuery('.linklist_content', this).click(function() {
			if(dc.linklist_marked !== null) {
				jQuery(dc.linklist_marked).removeClass("linklist_active");
			}
			jQuery(this).addClass("linklist_active");
			dc.linklist_marked = this;
			dc.current_linklist = thiz;
		}).mouseenter(function() {
			dc.mouse_in_linklist = true;
		}).mouseleave(function() {
			dc.mouse_in_linklist = false;
		}).dblclick(function(e) {
			if(jQuery(this).data('function') !== undefined) {
				var userFunc = jQuery(this).data('function');
				var funcCall = userFunc + "(this);";
				eval(funcCall);
				return;
			}
			if(jQuery(this).data("action") == "") {
				return;
			}
			var target = jQuery(e.target);
			//console.log(target.closest('form').attr("id"));
			setFormname(target.closest('form').attr("id"));
			loadCard(jQuery(this).data("action"));
		}).each(function() {
			if(jQuery(this).data('checked') == true) {
				jQuery(this).addClass("linklist_active");
				dc.linklist_marked = this;
				dc.current_linklist = thiz;
				setFormname(jQuery(this).closest('form').attr("id"));
			}
		});
		
		jQuery(this).data('linklist_init', true);
	});
	
	if(openCardOnStart === true) {
		loadCard(openCardAction, true);
		openCardOnStart = false;
	}
}

function openCardAfterLoading(){
	//debugger;
	if(openCardOnStart === true) {
		loadCard(openCardAction, true);
		openCardOnStart = false;
	}
}

function sortableHelper (e, tr) {
	var $originals = tr.children();
	var $helper = tr.clone();
	$helper.children().each(function(index) {
		// Set helper cell sizes to match the original sizes
		$(this).width($originals.eq(index).width());
	});
	return $helper;
}

function makeSortable(_linklist) {
	_linklist.sortable({
		'axis' : 'y',
		'items' : '.linklist_content',
		handle: '.sorticon',
		stop: function(event, ui) {
			if(dc.reorder_call !== null) {
				dc.reorder_call.abort();
			}
			
			serialized = _linklist.sortable('serialize');
			reorderCall = jQuery.post("?action=" + _linklist.data("sortableupdateaction"), serialized, function(output, status, xhr) {
				if(xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
					window.location.replace("/dc/");
				} 
			});
		},
		helper: sortableHelper
	});
}

function initForm() {
	$('#overlayContent input.date').each(function() {
		$("#ui-datepicker-div").remove();

		if(jQuery(this).data('datepicker_init') === true) return;
		$.datepicker.setDefaults(
		  $.extend(
			{'dateFormat':'dd.mm.yy'},
			$.datepicker.regional['de']
		  )
		);
		jQuery(this).datepicker({
		   prevText: '&#x3c;zurück', prevStatus: '',
			prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: '',
			nextText: 'Vor&#x3e;', nextStatus: '',
			nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: '',
			currentText: 'heute', currentStatus: '',
			todayText: 'heute', todayStatus: '',
			clearText: '-', clearStatus: '',
			closeText: 'schließen', closeStatus: '',
			monthNames: ['Januar','Februar','März','April','Mai','Juni',
			'Juli','August','September','Oktober','November','Dezember'],
			monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
			'Jul','Aug','Sep','Okt','Nov','Dez'],
			dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		  showMonthAfterYear: false,
		  showOn: 'both',
		  buttonImage: 'media/img/calendar.png',
		  buttonImageOnly: true,
		} 
	  );
	  jQuery(this).data('datepicker_init', true);
		
	});
	
	$('#overlayContent form').submit(function() {
		return false;
	});
}

function initDatepicker() {
	//$('#mainContent input.date').datepicker();
}

jQuery(document).ready(function() {
	initLinklist();
	initDatepicker();
	
// click auf document
}).click(function(e) {
	if(dc.current_linklist !== null && dc.mouse_in_linklist === false && e.target.nodeName.toLowerCase() != 'a') {
		// unmark all linklist 
		jQuery('.linklist_content', dc.current_linklist).removeClass("linklist_active");
		dc.linklist_marked = null;
	}
	
// keyboardtaste druecken und halten (steuerung der linkliste mit pfeiltasten
}).keydown(function (event) {

	// IC - AM - 20171012 ---
	/*if(dc.overlay_mode === true && event.keyCode == 27) { // ESC
		if(jQuery('body').hasClass("ckeditor_maximized")) return;
		event.preventDefault(); 
		disableOverlay();
		return;
	}*/
	// IC - AM - 20171012 +++
	
    switch(event.keyCode) {
        //arrow down
        case 40:
        	var nextRow = jQuery(dc.linklist_marked).nextAll('.linklist_content:visible:first');
        	if(nextRow.length == 0) {
        		return;
        	}
        	nextRow.addClass("linklist_active");
            jQuery(dc.linklist_marked).removeClass("linklist_active");
            dc.linklist_marked = nextRow;
            break;
        //arrow up
        case 38:
        	var prevRow = jQuery(dc.linklist_marked).prevAll('.linklist_content:visible:first');
        	if(prevRow.length == 0) {
        		return;
        	}
        	prevRow.addClass("linklist_active");
            jQuery(dc.linklist_marked).removeClass("linklist_active");
            dc.linklist_marked = prevRow;
            break;

    }
    
// keyboardtaste druecken
}).keypress(function(event) {
	if(dc.linklist_marked === null) {
		return;
	}
	
	if(event.keyCode == 13) {
		jQuery(dc.linklist_marked).dblclick();
	}
// IC - AM - 20171012 ---
}).keyup(function(event) {
	
    if (dc.overlay_mode === true && event.keyCode == 27) { // ESC
        if (jQuery('body').hasClass("ckeditor_maximized")) {
            return;
        }
        event.preventDefault();
        disableOverlay();
        return;
    }
});
// IC - AM - 20171012 +++


function reloadList() {


	try{
		tabulator.setPage(tabulator.getPage());
	}catch(e){
		document.location = replaceUrlParam(String(document.location), 'action', "");
	}
	
	/*jQuery('#mainContent .requestLoader').show();

	if (useTabulator) {
		selectedData = tabulator.getSelectedData();
		if(!selectedData || selectedData.length == 0){

			document.location = replaceUrlParam(String(document.location), 'action', "");
			setTimeout(function() {
				document.location = replaceUrlParam(String(document.location), 'action', "");
			}, 10);
		} else {
			tabulator.setData();
			tabulator.redraw();
		}
		
	} else {
		document.location = replaceUrlParam(String(document.location), 'action', "");
		setTimeout(function() {
			document.location = replaceUrlParam(String(document.location), 'action', "");
		}, 10);
	}

	
	return;*/
}

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1' + paramValue + '$2');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
    }
    return newUrl
}

function gotoLocation(_href) {
	document.location = _href;
}

/* ==========================================================================
Overlay Functions
========================================================================== */
function createOverlay() {
	dc.linklist_marked = null;
	dc.current_linklist = null;
	
	if(dc.overlay_mode === true) {
		return;
	}
	
	dc.overlay_mode = true;
	jQuery('#overlay').show();
	
	// overlay wrapper
	jQuery('#overlayWrapper').show();
	
	jQuery('#overlayLoader').show();
}

function disableOverlay() {
	//debugger;
	// Um aus Ticketkarte, welche mit ticketlink geöffnet wurde rauszukommen
	history.pushState(null, null, replaceUrlParam(replaceUrlParam(String(document.location), 'action', ""),'ticket_link', ""));
	dc.overlay_mode = false;
	jQuery('#overlay').hide();
	jQuery('#overlayContent').html("").hide();
	jQuery('#overlayWrapper').hide();
	jQuery('#overlayLoader').hide();
	jQuery('body').removeClass("ckeditor_maximized");
	reloadList();

}

function getFormData(_form) {
	for ( instance in CKEDITOR.instances ) {
        CKEDITOR.instances[instance].updateElement();
    }
	
	return _form.serialize();
}

/**
 * Absenden von requests ausserhalb vom overlay
 * 
 * @param _action
 * @param _load_without_check
 * @param _confirmtext
 * @returns {Boolean}
 */
function sendRequest(_action, _load_without_check, _confirmtext) {
	// variable zum pruefen ob in einer linkliste ein element markiert wurde
	var load_without_check = _load_without_check || false; 
	
	if(load_without_check === false) {
		var currentMarkedLinklistRow = jQuery('.linklist_active', jQuery('#' + dc.current_formname));
		
		if(dc.current_linklist === null || currentMarkedLinklistRow.length <= 0) {
			return;
		}
		var input_id = currentMarkedLinklistRow.data('inputid');
		jQuery('input.selected_linklist_row', jQuery('#' + dc.current_formname)).val(input_id);
	}
	
	var confirmtext = _confirmtext || false;
	if(confirmtext !== false && confirmtext != "") {
		if(!confirm(confirmtext)) {
			return false;
		}
	}
	
	if(dc.overlay_mode === true) {
		jQuery('#overlayLoader').show();
	} else {
		jQuery('#mainContent .requestLoader').show();
	}
	
	jQuery('#' + dc.current_formname).attr("action", "?action=" + _action);
	jQuery('#' + dc.current_formname).submit();
}


function loadCardNewList(_action, _load_without_check, _confirmtext, _closeOverlay, _customFormData){
	var useTabulatorTmp = useTabulator;
	useTabulator = false;
	loadCard(_action, _load_without_check, _confirmtext, _closeOverlay, _customFormData);
	useTabulator = useTabulatorTmp;
}


function loadOrganigrammSpace() {
	alert('Function called on div click!');
}

/**
 * Karte im overlay laden
 * 
 * @param _action
 * @param _load_without_check
 * @param _confirmtext
 * @param _closeOverlay
 * @returns {Boolean}
 */
function loadCard(_action, _load_without_check, _confirmtext, _closeOverlay, _customFormData, tabulator_row) {
	var confirmtext = _confirmtext || false;
	var closeOverlay = _closeOverlay || false;
	var action = _action || "";
	var currentMarkedLinklistRow;
	if(!useTabulator){
		currentMarkedLinklistRow = jQuery('.linklist_active', jQuery('#' + dc.current_formname));
	}
	
	
	
	var customFormData = _customFormData || false;
	
	// variable zum pruefen ob in einer linkliste ein element markiert wurde
	var load_without_check = _load_without_check || false; 

	// wenn ein listenelement markiert werden MUSS und keins markiert ist, dann nichts machen
	if(!useTabulator && load_without_check === false) {
		if(dc.current_linklist === null || currentMarkedLinklistRow.length <= 0) {
			return;
		}
	}
	
	var row;
	if(useTabulator && !openCardOnStart) {
		row = $('#' + dc.current_formname + ' div .tabulator-selected .tabulator-cell');
		if (!row.length && (action == 'edit' || action == 'edit_service_item')){
			return;
		}
	}

			
	// wenn bestaetigungstext vorhanden ist user auf Abbrechen klickt, dann return
	if(confirmtext !== false && confirmtext != "") {
		if(!confirm(confirmtext)) {
			return false;
		}
	}
	
	// Wenn listenelement martkiert ist, dann die inputid uebergeben
	if(currentMarkedLinklistRow  && currentMarkedLinklistRow.length > 0) {
		var input_id = currentMarkedLinklistRow.data('inputid');
		jQuery('input.selected_linklist_row', jQuery('#' + dc.current_formname)).val(input_id);
	}
	
	// wird benoetigt damit die Inhalte des fckeditors uebertragen werden koennen
	for ( instance in CKEDITOR.instances ) {
        CKEDITOR.instances[instance].updateElement();
    }
	// heller overlay ueber die ganze seite wird erstellt
	createOverlay();
	
	// loader wird engezeigt
	jQuery('#overlayLoader').show();
	
	// Sammeln von formulardaten
	var formData2;
	try {
		formData2 = new FormData($('#' + dc.current_formname)[0]);
	} catch(e){	
		formData2= new FormData();
	}
	if(customFormData !== false) {
		formData2 = customFormData;
	} else {
		if (!useTabulator) {
			formData2 = new FormData($('#' + dc.current_formname)[0]);
				if(typeof(currentMarkedLinklistRow) !== 'undefined' && currentMarkedLinklistRow.length > 0) {
					$.each(currentMarkedLinklistRow.data(), function(idx, el) {
						formData2.append("data-" + idx, el);
					});
				}
		} else {
			if (/*$('#'+dc.current_formname+'').length && */openCardOnStart){
				//var formData2 = new FormData();
				//var filename = $('#'+dc.current_formname+' input[name=filename]').val();
				//formData2.append("filename",filename);
				formData2.append("input_id",dc.current_input_id);
			}else if(row.length /*&& (action == 'edit' || action ==  'new')*/){
				//var formData2 = new FormData();
				//var filename = $('#'+dc.current_formname+' input[name=filename]').val();
				row.each(function(index,element){
					//console.log(element.getAttribute("tabulator-field"),element.firstChild.nodeValue);
					formData2.append(element.getAttribute("tabulator-field"),element.firstChild.nodeValue);
				});

			}
			formData2.append("filename",filename);
			// IC - AM - HD365 ---
			formData2.append("serial_no",dc.serial_no);
			formData2.append("document_no",dc.document_no);
			formData2.append("document_type",dc.document_type);
			formData2.append("ticket_no_b64",dc.ticket_no_b64);
			// IC - AM - HD365 +++
			
		// Display the key/value pairs
		/*console.log("Formdata:");
		for (var pair of formData2.entries()) {
			console.log(pair[0]+ ', ' + pair[1]); 
		}*/
		}
	}
	if (tabulator_row){
		for (var key in tabulator_row.getData()) {
			formData2.append(key,tabulator_row.getData()[key]);
		}
	}
	if (show_document_cue){
		formData2.append("show_document_cue",show_document_cue);
	}
	
	if(closeOverlay === true) {
		formData2.append("force_close", 1);
	} else {
		formData2.append("force_close", 0);
	}

	// AJAX POST request abschicken. Formulardaten werden mit HTML5 FormData gesammelt und verschickt.
	// Dadurch ist es moeglich auch Dateien zu ubertragen (Bildupload moeglich).
	// Fuer den Dateiupload muessen die variablen processData, cache und contentType auf false gesetzt werden
	 $.ajax({
		 url: "?action=" + action,
		 type: 'POST',
		 data: formData2,
		 mimeType: "multipart/form-data",
		 cache: false,
		 processData: false, // Don't process the files
		 contentType: false, // Set content type to false as jQuery will tell the server its a query string request
		 success: function(output, status, xhr) {
			 //if(xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
			//	window.location.replace("/dc/");
			//} else {
				//console.log(window.location);
				//debugger;
				if(closeOverlay === true && xhr.getResponseHeader('EDIT_ERROR') != 1) {
					disableOverlay();
				} else {
					try{
						jQuery('#overlayContent').html(output);
						//console.log("Output:"+output);
					} catch (e){
						//console.log(e.message);
						//jQuery('#overlayContent').html('<error>Ooops: Something went wroong</error>')
					}
					jQuery('#overlayLoader').hide();
					jQuery('#overlayContent').show();
					//if(!useTabulator){
						initForm();
						initLinklist();
					//} else {
						//initForm();
					//}
				}
				
			//}
		 },
		 error: function(jqXHR, textStatus, errorThrown) {
			 console.log(jqXHR);
			 console.log('ERRORS: ' + textStatus);
			 console.log(errorThrown);
		 }
	});
}

function loadCardFromCard(_action, _confirmtext) {
	var confirmtext = _confirmtext || false;
	var closeOverlay = false;
	var action = _action || "";	
		
			
	// wenn bestaetigungstext vorhanden ist user auf Abbrechen klickt, dann return
	if(confirmtext !== false && confirmtext != "") {
		if(!confirm(confirmtext)) {
			return false;
		}
	}
	
	// wird benoetigt damit die Inhalte des fckeditors uebertragen werden koennen
	for ( instance in CKEDITOR.instances ) {
        CKEDITOR.instances[instance].updateElement();
    }
	// heller overlay ueber die ganze seite wird erstellt
	createOverlay();
	
	// loader wird engezeigt
	jQuery('#overlayLoader').show();
	
	// Sammeln von formulardaten
	var formData2;
	try {
		formData2 = new FormData($('#' + dc.current_formname)[0]);
	} catch(e){	
		formData2= new FormData();
	}

	formData2.append("filename",filename);

	// Display the key/value pairs
	console.log("Formdata:");
	for (var pair of formData2.entries()) {
		console.log(pair[0]+ ', ' + pair[1]); 
	}
	formData2.append("force_close", 0);
	

	// AJAX POST request abschicken. Formulardaten werden mit HTML5 FormData gesammelt und verschickt.
	// Dadurch ist es moeglich auch Dateien zu ubertragen (Bildupload moeglich).
	// Fuer den Dateiupload muessen die variablen processData, cache und contentType auf false gesetzt werden
	 $.ajax({
		 url: "?action=" + action,
		 type: 'POST',
		 data: formData2,
		 mimeType: "multipart/form-data",
		 cache: false,
		 processData: false, // Don't process the files
		 contentType: false, // Set content type to false as jQuery will tell the server its a query string request
		 success: function(output, status, xhr) {
			 //if(xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
			//	window.location.replace("/dc/");
			//} else {
				//console.log(window.location);
				//debugger;
				if(closeOverlay === true && xhr.getResponseHeader('EDIT_ERROR') != 1) {
					disableOverlay();
				} else {
					try{
						jQuery('#overlayContent').html(output);
						//console.log("Output:"+output);
					} catch (e){
						console.log(e.message);
						jQuery('#overlayContent').html('<error>Ooops: Something went wroong</error>')
					}
					jQuery('#overlayLoader').hide();
					jQuery('#overlayContent').show();
				}
				
			//}
		 },
		 error: function(jqXHR, textStatus, errorThrown) {
			 console.log(jqXHR);
			 console.log('ERRORS: ' + textStatus);
			 console.log(errorThrown);
		 }
	});
}

function download_url(url, filename) {
	
	fetch(url).then(function(t) {
		return t.blob().then(function(b){
				if (b.type != "text/html; charset=utf-8"){ // weil download_file.php einen redirect bei nicht gefundener Datei macht
					var a = document.createElement("a");
					a.href = URL.createObjectURL(b);
					a.setAttribute("download", filename);
					a.click();
					return true;
				} else {
					alert("Fehler beim Dateidownload. Bitte wenden Sie sich an Ihren Administrator.");
					return false;
				}
			}
		);
	});
}
function submit_post_via_hidden_form(url, params) {
    var f = $("<form target='_blank' method='POST' style='display:none;'></form>").attr({
        action: url
    }).appendTo(document.body);

    for (var i in params) {
        if (params.hasOwnProperty(i)) {
            $('<input type="hidden" />').attr({
                name: i,
                value: params[i]
            }).appendTo(f);
        }
    }

    f.submit();

    f.remove();
}
