window.onerror = function (message, url, lineNo){
    alert('Error: ' + message + '\n' + 'Line Number: ' + lineNo);
    return true;
}

function setRoomData() {
    $.ajax({
        type: "POST",
        url: '/setObjectName.php',
        data: {
            'name': activeRoomName,
            'room': $('#input-room').val(),
            'floor': $('#floor').html(),
            'description': $('#input-description').val()
        },
        success: function () {
            loadRooms();
        }
    });
}
function search() {
	var resp = [];
    $.ajax({
        type: "GET",
        url: '/searchRoom.php',
        data: {'room': $('#searching').val()},
        success: function () {
			//alert(room);
			//resp.push(data);
            console.log("success function");
		console.log('#room');
			console.log(name);
			console.log('#floor');
        }
    });
}

var defaultMaterial = new JSC3D.Material('', 0, 0xFFFFFF, 0, true),
    activeRoom = null,
    activeRoomName = null,
    activeRoomNameOrigMaterial = null;


function highlightMeshByName(name, elevator) {

    activeRoomName = name;
	//console.log(name);
	//console.log(elevator);
    if (activeRoom !== null) {
        activeRoom.setMaterial(activeRoomOrigMaterial);
    }

    var objs = viewer.getScene().getChildren();
    for (var y = 0; y < objs.length; y++) {


        var _obj = objs[y];

        if (_obj.name == name) {
        
            activeRoomOrigMaterial = _obj.material; 

            if (elevator == 1) {
                _obj.setMaterial(new JSC3D.Material('', 0, 0x00ff00, 0, true));
				//console.log('som el 1');
            } else if (elevator == 2) {
                _obj.setMaterial(new JSC3D.Material('', 0, 0xff9900, 0, true));
				//console.log('som el 2');
			} else {
                _obj.setMaterial(new JSC3D.Material('', 0, 0xffff00, 0, true));
				
        
		}
            
            activeRoom = _obj;
        }
    }

    viewer.update();
}

/*
 * rooms
 */
var rooms = [];

function loadRooms() {
    $('#menu').html('');
    $('#menu-select').html('');

    $.ajax({
        type: "POST",
        url: '/getRooms.php',
        dataType: 'json',
        data: {'floor': $('#floor').html()},
        success: function (data) {
            rooms = data;

            var x;
            for (x = 0; x < rooms.length; x++) {
                var $room = $('<div data-obj="' + rooms[x]['name'] + '">' + rooms[x]['room'] + '</div>');
                $('#menu').append($room);
                if(rooms[x]['room'] !== ''){
                    var $roomSelect = $(`<option  data-obj="` + rooms[x]['name'] + `" value=${rooms[x].room}>` + rooms[x]['room'] + '</option>');
                    $('#menu-select').append($roomSelect);
                }
            
                if (rooms[x]['elevator'] > 0) {
                    if (viewer.getScene() !== null) {
                        var objs = viewer.getScene().getChildren();
                        for (var y = 0; y < objs.length; y++) {
                            var _obj = objs[y];

                            if (_obj.name == rooms[x]['name']) {
                            
                            
                            
                                if (rooms[x]['elevator'] == 1) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0x00ff00, 0, true));
                                } else if (rooms[x]['elevator'] == 2) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0xff9900, 0, true));
                                } else if (rooms[x]['elevator'] == 4) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0x9e9e61, 0, true));
								} else if (rooms[x]['elevator'] == 5) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0x665c7a, 0, true));
                                } else if (rooms[x]['elevator'] == 6) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0x5c7a29, 0, true));
                                } else if (rooms[x]['elevator'] == 7) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0x993d29, 0, true));
                                } else if (rooms[x]['elevator'] == 8) {
                                    _obj.setMaterial(new JSC3D.Material('', 0, 0x94663b, 0, true));
									
                                }

                                viewer.update();
                            }
                        }
                        
                        
                                            (function (_roomName, _roomDescription, _elevator) {
						//console.log('idem room click');
                        $room.click(function () {
                        
                        
							
                        
                            var $this = $(this);
                            var obj = $this.attr('data-obj');

                            $('#input-room').val(_roomName);
                            $('#input-description').val(_roomDescription);
                            setRoomNumberOnPanel(_roomName, _roomDescription);
							//console.log('idem highlightMeshByName click');
                            highlightMeshByName(obj, _elevator);
                        });
                        $( "#menu-select" ).change(function() {
                            var $thisObj = $(this).find('option:selected').attr('data-obj');
                            if($(this).find('option:selected').val() === _roomName){
                                setRoomNumberOnPanel(_roomName, _roomDescription);
                            }
                            highlightMeshByName($thisObj, _elevator);
							
                          });
                    })(rooms[x]['room'], rooms[x]['description'], rooms[x]['elevator']);
                    } 

                } else {
					
								
                
                
                    (function (_roomName, _roomDescription, _elevator) {
						//console.log('idem room click');
                        $room.click(function () {
                        
                        
							
                        
                            var $this = $(this);
                            var obj = $this.attr('data-obj');

                            $('#input-room').val(_roomName);
                            $('#input-description').val(_roomDescription);

                            setRoomNumberOnPanel(_roomName, _roomDescription);
							//console.log('idem highlightMeshByName click');
                            highlightMeshByName(obj, _elevator);
                        });

                        $( "#menu-select" ).change(function() {
                            var $thisObj = $(this).find('option:selected').attr('data-obj');
                            if($(this).find('option:selected').val() === _roomName){
                                setRoomNumberOnPanel(_roomName, _roomDescription);
								zoom();
                            }
                            highlightMeshByName($thisObj, _elevator);
							

                          });
                    })(rooms[x]['room'], rooms[x]['description'], rooms[x]['elevator']);
                }


            }
            
            
                
    if(typeof onAfterRoomsLoaded == 'function'){
        onAfterRoomsLoaded();
        onAfterRoomsLoaded = null;
    }
        }
    });

}


var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || isMobile) {
    $('#menu-floor-select').css({display:'block'});
    $('#menu-floor').css({display:'none'});

    $('#menu-select').css({display:'block'});
    $('#menu').css({display:'none'});
	$('#menu-select').css({display:'block'});
	$('#hladajPC').css({display:'none'});
	$('#hladaj').css({display:'block'});
}


/*
 * floorss
 */

var floors = [
	{name: '1NP', 'obj': 'prveposchodie.obj', id:1},
	{name: '2NP', 'obj': '2poschodie.obj', id:2},
	{name: '3NP', 'obj': '3poschodie.obj', id:3},
	{name: '4NP', 'obj': '4poschodie.obj', id:4},
	{name: '5NP', 'obj': '5patr.obj', id:5},
    {name: '6NP', 'obj': 'poschodie6.obj', id:6},
	{name: '7NP', 'obj': '7patro.obj', id:7},
	{name: '8NP', 'obj': '8patro.obj', id:8}
];
for (x = 0; x < floors.length; x++) {
    var $floor = $(`<div data-id="${floors[x].id}" data-obj="` + floors[x]['obj'] + '">' + floors[x]['name'] + '</div>');
    $('#menu-floor').append($floor);

    var $floorSelect = $(`<option  data-obj="` + floors[x]['obj'] + `" value=${floors[x].id}>` + floors[x]['name'] + '</option>');
    $('#menu-floor-select').append($floorSelect);

    $floor.click(function () {
        var $this = $(this);
        var floor = $this.attr('data-obj');
        const floorId = $this.attr('data-id');
		
        $("#menu-floor-select").val(floorId);
		
		//console.log(floor);
        viewer.setParameter('SceneUrl', 'models_converted/' + floor);			//set the URL of 3D model file
        viewer.init();
				//always need init()
        viewer.update();

        
        $('#floor').html($this.html());
    });
}




$( "#menu-floor-select" ).change(function() {
	
    var $this = $(this);
	$this.blur();
    //const floorId = $(this).val();
    var flor = floors.find(item => item.id == $this.val());
    //console.log(floor);
    viewer.setParameter('SceneUrl', 'models_converted/' + flor.obj);			//set the URL of 3D model file
    viewer.init();
            //always need init()
    viewer.update();
	
    
    $('#floor').html(flor.name);
	zoom();
  });

function nl2br(str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function setRoomNumberOnPanel(number, _roomDescription) {
    $('#room').html(number);
    $('#menu-select').val(number);

    if (_roomDescription) {
        $('#room-description').html(nl2br(_roomDescription));
    } else {
        $('#room-description').html('');
    }
}


//	JSC3D.console.setup('main_frame', '120px');				//set the frame to use

var canvas = document.getElementById('cv');				//get the canvas to draw on
var viewer = new JSC3D.Viewer(canvas);					//initialize a new 3D viewer object
viewer.onloadingcomplete = function() {
    loadRooms();
};
var logoTimerID = 0;							//???
viewer.setParameter('SceneUrl', 'models_converted/' + floors[0].obj);			//set the URL of 3D model file
viewer.setParameter('InitRotationX', 0);				//
viewer.setParameter('InitRotationY', 0);				//Init Rotate X,Y,Z, but how to auto get best rotation view?
viewer.setParameter('InitRotationZ', 0);				//
viewer.setParameter('MipMapping', JSC3D.PlatformInfo.supportWebGL ? 'off' : 'on');
viewer.setParameter('ModelColor', '#333300');				//set model color, maybe can add option to fit with our printer's material's color!
viewer.setParameter('BackgroundColor1', '#FFFFFF');			//set bg color 1, &
viewer.setParameter('BackgroundColor2', '#FFFFFF');			//set bg color 2, to get gradient! can adjust to site theme
viewer.setParameter('RenderMode', 'texture');				//set render mode to "smooth", which should always be the case
viewer.setParameter('setDefinition', 'high');
//viewer.setParameter('InitRotationZ', 50);
viewer.setParameter('InitRotationX', -25);
viewer.init();								//always need init()
viewer.update();							//always do update() to put it on the screen

viewer.enableDefaultInputHandler(true);


$(function(){
      $( "#searching" ).autocomplete({
      source: "/searchRoom.php",
      minLength: 2,
      select: function( event, ui ) {
        var item = ui.item;
        
        $('#menu-floor div:contains("' + item.floor + '")').click();
        
        onAfterRoomsLoaded = function(){
            $('#menu div[data-obj="' + item.id + '"]').click();
        }
      }
    });
});
function zoom() {
		//document.body.style.width = screen.availWidth;
		//document.body.style.height =screen.availHeight;
                //document.body.style.zoom = 0.70;
				//this.blur();
        }
        
