define(['jquery'], function($)
{
	var ClaPeopleOrgchart = function(){
	};

	ClaPeopleOrgchart.prototype.currentOrgchartVersion = 'photo';

	ClaPeopleOrgchart.prototype.init = function(datasource, filename)
	{
        const viewOptionsFormEl = document.querySelector('.js-view-options-form');
        const verticalLevelInput = document.querySelector('.js-vertical-level-value');
        const url = new URL(window.location.href);
        const searchParams = new URLSearchParams(url.search);
        const urlVerticalLevel = searchParams.get('verticalLevel'); // true
        var verticalLevel = 4;

        if (urlVerticalLevel) {
            verticalLevel = Number(urlVerticalLevel);
        } else if (localStorage.getItem("verticalLevel")) {
            verticalLevel = Number(localStorage.getItem("verticalLevel"));
        }

        verticalLevelInput.value = verticalLevel;

        viewOptionsFormEl.addEventListener('submit', function(event) {
            localStorage.setItem("verticalLevel", event.target.elements['verticalLevel'].value);
        });


		if (datasource != null)
		{
			var chartContainer = $('#chart-container');

			// only display orgchart if there's data to show.
			var opts = {
				'data' : datasource,
				'nodeTitle': 'nodeTitlePro',
				'nodeContent' : 'nodeContentPro',
				'pan': true,
				'zoom': false,
				'zoominLimit': 1.4,
				'zoomoutLimit': 0.2,
                'verticalLevel': verticalLevel,
				'exportButton': false,
				'exportFilename': filename
			};
			window.oc_test = chartContainer.orgchart(opts);

            window.oc_test.setChartScale($('.orgchart'), 1);

            var zoomEvent

            $('#zoomOut').on('mousedown touchstart',function(){
                var newScale  = 1 + -0.06;
                zoomEvent = setInterval(function(){
                    window.oc_test.setChartScale($('.orgchart'), newScale);
                },100);
            });
            $('#zoomIn').on('mousedown touchstart',function(){
                var newScale  = 1 + 0.06;
                zoomEvent = setInterval(function(){
                    window.oc_test.setChartScale($('.orgchart'), newScale);
                },100);
            });
            $('#zoomOut, #zoomIn').on('mouseup touchend touchcancel',function(){
                clearInterval(zoomEvent);
            })
            $('#zoomOut, #zoomIn').on("contextmenu",function(){
                return false;
            });


            $('.orgchart').addClass('noncollapsable'); // deactivate collapsability

            var chartOuterContainer = $('#chart-container-outer');
            var chartOuterWidth = chartOuterContainer.width();
            var chartOuterHeight = chartOuterContainer.height();
            var chartTable = chartContainer.find('table').first();
            var chartTableWidth = chartTable.width();
            var chartTableHeight = chartTable.height();

            chartTable.addClass('table table-borderless');
            chartContainer.css('width', '100%');
            chartContainer.css('height', '100%');

            //center Orgchart upon open and zoom in/out
            $('.orgchart').css('width', chartTableWidth);
            chartContainer.scrollLeft((chartContainer[0].scrollWidth - chartContainer.width())/2);

            if (!orgchart_is_preview)
            {
                if (chartTableHeight > chartOuterHeight) {
                    chartOuterContainer.css('height', window.outerHeight - 330 + 'px');
                }
            } else {
                chartContainer.css('height', window.outerHeight - 183 + 'px');
            }

            //If using the side menu option the charts container's height is adjusted
            if($('button[name="side-menu-button"]').is(':hidden')) {
                chartOuterContainer.css('height', window.innerHeight - 303 + 'px');
            } else {
                chartOuterContainer.css('height', window.innerHeight - 243 + 'px');
            }
            $('.hover-link-button + a').on('dragstart drop', function(e){
                e.preventDefault();
                return false;
            });

			// create our own export button. This is mainly a copy-paste of the code in the orgchart
			// library with the addition of a temporary change to the height/width of
			// #orgchart-outer-container to get around an annoying bug with the html2canvas library
			// cutting off the image when exporting. - tezmc
			var $exportBtn = $('<button>', {
				'class': 'orgchart-export-btn btn btn-success ml-2 ' + (opts.chartClass !== '' ? ' ' + opts.chartClass : ''),
				'text': 'Export',
				'click': function(e) {
					// temporarily set the dimensions of outer container to size of orgchart table
					var outerChart = $('#chart-container-outer');
					outerChart.css('width', chartTable.width() + 50);
					outerChart.css('height', chartTable.height() + 50);

					e.preventDefault();
					if ($(this).children('.spinner').length) {
						return false;
					}
					var $mask = chartContainer.find('.mask');
					if (!$mask.length) {
						chartContainer.append('<div class="mask"><i class="fa fa-circle-o-notch fa-spin spinner"></i></div>');
					} else {
						$mask.removeClass('d-none');
					}

                    $('#chart-container, .orgchart').css({
                        'height': '100%',
                    });
					$('.orgchart .verticalNodes ul:first-child > li').css('margin-left', '120px');

                    var sourceChart = chartContainer.addClass('canvasContainer').find('.orgchart:visible').get(0);

                    var flag = opts.direction === 'l2r' || opts.direction === 'r2l';
					html2canvas(sourceChart, {
						// 'logging': true,
                        'scale': 2,
						'useCORS': true,
						'width': flag ? sourceChart.clientHeight : sourceChart.clientWidth,
						'height': flag ? sourceChart.clientWidth : sourceChart.clientHeight,
						'onclone': function(cloneDoc) {
							$(cloneDoc).find('.canvasContainer').css('overflow', 'visible')
								.find('.orgchart:visible:first').css('transform', '');
						},
						'onrendered': function(canvas) {
							chartContainer.find('.mask').addClass('d-none');
							if (opts.exportFileextension && opts.exportFileextension.toLowerCase() === 'pdf') {
								var doc = {};
								var docWidth = Math.floor(canvas.width * 0.2646);
								var docHeight = Math.floor(canvas.height * 0.2646);

								if (docWidth > docHeight) {
									doc = new jsPDF('l', 'mm', [docWidth, docHeight]);
								} else {
									doc = new jsPDF('p', 'mm', [docHeight, docWidth]);
								}

								doc.addImage(canvas.toDataURL(), 'png', 0, 0);
								doc.save(opts.exportFilename + '.pdf');
							} else {
                                var isWebkit = 'WebkitAppearance' in document.documentElement.style;
								var isFf = !!window.sidebar;
								var isEdge = navigator.appName === 'Microsoft Internet Explorer' || (navigator.appName === "Netscape" && navigator.appVersion.indexOf('Edge') > -1);

								if ((!isWebkit && !isFf) || isEdge) {
									window.navigator.msSaveBlob(canvas.msToBlob(), opts.exportFilename + '.png');
								}
								else {
                                    $('.js-orgchart-controls').find('.oc-download-btn').attr('href', canvas.toDataURL())[0].click();
								}
							}
						}
					})
						.then(function() {
							chartContainer.removeClass('canvasContainer');
						}, function() {
							chartContainer.removeClass('canvasContainer');
						});
					// reset dimensions of outer container
					outerChart.css('width', '100%');
					outerChart.css('height', window.innerHeight - 303 + 'px');
                    if($('button[name="side-menu-button"]').is(':hidden')) {
                        chartOuterContainer.css('height', window.innerHeight - 303 + 'px');
                    } else {
                        chartOuterContainer.css('height', window.innerHeight - 243 + 'px');
                    }
                }
			});

            //Disable orgchart when orgchart is to big for html2Canvas to export on certain browsers
            var browserName = '';

            function getBrowser(){
                isIE = /*@cc_on!@*/false || !!document.documentMode;
                isEdge = !isIE && !!window.StyleMedia;
                if(navigator.userAgent.indexOf("Chrome") != -1 && !isEdge) {
                    browserName = 'chrome';
                }
                else if(navigator.userAgent.indexOf("Firefox") || navigator.userAgent.indexOf("Safari") != -1 ) {
                    browserName = 'firefox/safari';
                }
                else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) {
                    browserName = 'ie';
                }
                else if(isEdge) {
                    browserName = 'edge';
                }
                else {
                    browserName = 'other-browser';
                }
                return browserName;
            };
            getBrowser();

            switch (browserName) {
                case 'ie':
                    if (chartTable.width() > 22528 || chartTable.height() > 20992) {
                        $exportBtn.prop('disabled', true);
                        $exportBtn.prop('title', lmsg('orgchart.export.largeerror'));
                    } else if ((chartTable.width() > 8192 && chartTable.width() < 22528) || (chartTable.height() > 8192 && chartTable.height() < 20992)) {
                        $exportBtn.prop('disabled', true);
                        $exportBtn.prop('title', lmsg('orgchart.export.largeerror.ie'));
                    }
                    break;
                case 'chrome':
                    if (chartTable.width() > 22528 || chartTable.height() > 20992) {
                        $exportBtn.prop('disabled', true);
                        $exportBtn.prop('title', lmsg('orgchart.export.largeerror'));
                    } else if ((chartTable.width() > 16384 && chartTable.width() < 22528) || (chartTable.height() > 16384 && chartTable.height() < 20992)) {
                        $exportBtn.prop('disabled', true);
                        $exportBtn.prop('title', lmsg('orgchart.export.largeerror.chrome'));
                    }
                    break;
                case 'firefox/safari':
                    if (chartTable.width() > 22528 || chartTable.height() > 20992) {
                        $exportBtn.prop('disabled', true);
                        $exportBtn.prop('title', lmsg('orgchart.export.largeerror'));
                    }
                    break;
            }

            $('.js-orgchart-controls').append($exportBtn);

            if (!opts.exportFileextension || opts.exportFileextension.toLowerCase() !== 'pdf') {
				var downloadBtn = '<a class="oc-download-btn' + (opts.chartClass !== '' ? ' ' + opts.chartClass : '') + '"'
					+ ' download="' + opts.exportFilename + '.png"></a>';
				$exportBtn.after(downloadBtn);
			}

            // set the onclick behaviour for buttons in the UI
            var viewMode = 'photo';

            $('.js-org-chart-view-mode-toggle').click(function(e){
                var thisId = $(this).attr('id');

                if (thisId === 'text-version') {
                    $('.orgchart-user-photo').addClass('d-none');
                    viewMode = 'text';
                } else  {
                    $('.orgchart-user-photo').removeClass('d-none');
                    viewMode = 'photo';
                }
            });

        }
		else
		{
			console.error('cla_orgchart: datasource not defined');
		}
	};
	return ClaPeopleOrgchart;
});
