<commit_before>$(document).ready(()=>{
    let peer=null;
    let room=null;
    let localStream=null;
    let remoteStreams={};
    let userdata={
        username:'',
        usericon:null
    };
    let usersdata={};

    $.getJSON('/js/apikey.json',(data)=>{
        peer=new Peer({
            key:data.key,
            debug:3
        });
        peer.on('open',id=>{
            $('#status-icon').removeClass('status-icon-offline');
            $('#status-icon').addClass('status-icon-online');
            $('#skyway-statustxt').text('SkyWay Status : online');
        });
        peer.on('disconnected',()=>{
            $('#status-icon').addClass('status-icon-offline');
            $('#status-icon').removeClass('status-icon-online');
            $('#skyway-statustxt').text('SkyWay Status : offline');
        })
    });
    $('#usericonpit').on('change',e=>{
        let file=e.target.files[0];
        userdata.usericon=file;
        $('#localusericon').attr('src',URL.createObjectURL(file));
        $('#localusericon').on('load',()=>{
            if($('#localusericon').get(0).width>256||$('#localusericon').get(0).height>256){
                swal({
                    title: 'Icon Size Error!',
                    text: 'Please use images of 256px or less in height and width.',
                    icon: 'error',
                });
                userdata.usericon=null;
                $('#localusericon').attr('src','./img/usericon.png');
            }
            if($('#localusericon').get(0).width!==$('#localusericon').get(0).height){
                swal({
                    title: 'Icon Size Error!',
                    text: 'Please use square image',
                    icon: 'error',
                });
                userdata.usericon=null;
                $('#localusericon').attr('src','./img/usericon.png');
            }
        });
    });
    $('#joinroombtn').on('click',()=>{
        let roomname=$('#roomnameipt').val();
        let username=$('#usernameipt').val();
        userdata.username=username;
        usersdata[peer.id]=userdata;
        $('#localusername').text(username?username:peer.id);
        if(roomname){
            $('#roomnametxt').text(`Room : ${roomname}`);
            $('#joinroom').toggle();
            $('#chat').toggle();

            navigator.mediaDevices.getUserMedia({video:false,audio:true})
            .then(stream=>{
                localStream=stream;
                $('#myvideo').get(0).srcObject=stream;
                room=peer.joinRoom(roomname,{mode:'sfu',stream:stream});
                userdata.username=username;
                connect(room);
            })
            .catch(e=>{
                swal({
                    title: 'getUserMedia Error!',
                    text: 'Please check your microphone.',
                    icon: 'error',
                });
            });
        }
    });
    $('#leaveroombtn').on('click',()=>{
        room.close();
        room=null;
        localStream.getTracks().forEach(track => track.stop());
        localStream=null;
        userdata={};
        usersdata={};
        $('#myvideo').get(0).srcObject=null;
        removeChatUserElms();
        $('#joinroom').toggle();
        $('#chat').toggle();
    });
    $('#local-mutebtn').on('click',()=>{
        if($('#local-mutebtn').text()==='Mute'){
            localStream.getTracks().forEach(track=>track.enabled=false);
            $('#local-mutebtn').text('Unmute');
        }else{
            localStream.getTracks().forEach(track=>track.enabled=true);
            $('#local-mutebtn').text('Mute');
        }
    });

    let connect=_room=>{
        _room.on('open',()=>{
            _room.send(userdata);
        });
        _room.on('stream',stream=>{
            console.log(stream);
            addChatUserElm(stream.peerId);
            _room.send(userdata);
            remoteStreams[stream.peerId]=stream;
            $(`#${stream.peerId}-video`).get(0).srcObject=stream;
            $(`#${stream.peerId}-video`).get(0).play();
        })
        _room.on('data',msg=>{
            console.log(msg);
            if(msg.data.username){
                usersdata[msg.src]={
                    username:msg.data.username,
                    usericon:msg.data.usericon
                };
                $(`#${msg.src}-name`).text(msg.data.username);
                if(msg.data.usericon){
                    setTimeout(()=>{
                        const dataView = new Uint8Array(msg.data.usericon);
                        const dataBlob = new Blob([dataView]);
                        const url = URL.createObjectURL(dataBlob);
                        $(`#${msg.src}-icon`).attr('src',url);
                    },500);
                }
            }
        });
        _room.on('peerJoin',id=>{
            console.log(id);
        });
        _room.on('peerLeave',id=>{
            console.log(id);
            remoteStreams[id]=null;
            usersdata[id]=null;
            removeChatUserElm(id);
        });
    };
    let addChatUserElm=(id)=>{
        let _elm=`

${(usersdata[id]?usersdata[id].username:id)}

            <video id="${id}-video" autoplay></video>

                <button id="${id}-mutebtn" class="btn btn-secondary">Mute</button>

`;

        $('#chat-users').append(_elm);

        $(`#${id}-mutebtn`).on('click',()=>{
            if($(`#${id}-mutebtn`).text()==='Mute'){
                remoteStreams[id].getTracks().forEach(track=>track.enabled=false);
                $(`#${id}-mutebtn`).text('Unmute');
                $(`#${id}`).removeClass('active-user');
                $(`#${id}`).addClass('mute-user');
            }else{
                remoteStreams[id].getTracks().forEach(track=>track.enabled=true);
                $(`#${id}-mutebtn`).text('Mute');
                $(`#${id}`).removeClass('mute-user');
                $(`#${id}`).addClass('active-user');
            }
        })
    };

    let removeChatUserElm=(id)=>{
        $(`#${id}`).remove();
    }

    let removeChatUserElms=()=>{
        let elms=$('.chat-user');
        for(let i=0;i<elms.length;i++){
            if(elms[i].className.indexOf('local-user')===-1){
                elms[i].remove();
            }
        }
    };
});<commit_msg>add username save<commit_after>$(document).ready(()=>{
    let peer=null;
    let room=null;
    let localStream=null;
    let remoteStreams={};
    let userdata={
        username:'',
        usericon:null
    };
    let usersdata={};

    $('#usernameipt').val(localStorage.getItem('username'));

    $.getJSON('/js/apikey.json',(data)=>{
        peer=new Peer({
            key:data.key,
            debug:3
        });
        peer.on('open',id=>{
            $('#status-icon').removeClass('status-icon-offline');
            $('#status-icon').addClass('status-icon-online');
            $('#skyway-statustxt').text('SkyWay Status : online');
        });
        peer.on('disconnected',()=>{
            $('#status-icon').addClass('status-icon-offline');
            $('#status-icon').removeClass('status-icon-online');
            $('#skyway-statustxt').text('SkyWay Status : offline');
        })
    });
    $('#usericonpit').on('change',e=>{
        let file=e.target.files[0];
        userdata.usericon=file;
        $('#localusericon').attr('src',URL.createObjectURL(file));
        $('#localusericon').on('load',()=>{
            if($('#localusericon').get(0).width>256||$('#localusericon').get(0).height>256){
                swal({
                    title: 'Icon Size Error!',
                    text: 'Please use images of 256px or less in height and width.',
                    icon: 'error',
                });
                userdata.usericon=null;
                $('#localusericon').attr('src','./img/usericon.png');
            }
            if($('#localusericon').get(0).width!==$('#localusericon').get(0).height){
                swal({
                    title: 'Icon Size Error!',
                    text: 'Please use square image',
                    icon: 'error',
                });
                userdata.usericon=null;
                $('#localusericon').attr('src','./img/usericon.png');
            }
        });
    });
    $('#joinroombtn').on('click',()=>{
        let roomname=$('#roomnameipt').val();
        let username=$('#usernameipt').val();
        localStorage.setItem('username',username);
        userdata.username=username;
        usersdata[peer.id]=userdata;
        $('#localusername').text(username?username:peer.id);
        if(roomname){
            $('#roomnametxt').text(`Room : ${roomname}`);
            $('#joinroom').toggle();
            $('#chat').toggle();

            navigator.mediaDevices.getUserMedia({video:false,audio:true})
            .then(stream=>{
                localStream=stream;
                $('#myvideo').get(0).srcObject=stream;
                room=peer.joinRoom(roomname,{mode:'sfu',stream:stream});
                userdata.username=username;
                connect(room);
            })
            .catch(e=>{
                swal({
                    title: 'getUserMedia Error!',
                    text: 'Please check your microphone.',
                    icon: 'error',
                });
            });
        }
    });
    $('#leaveroombtn').on('click',()=>{
        room.close();
        room=null;
        localStream.getTracks().forEach(track => track.stop());
        localStream=null;
        userdata={};
        usersdata={};
        $('#myvideo').get(0).srcObject=null;
        removeChatUserElms();
        $('#joinroom').toggle();
        $('#chat').toggle();
    });
    $('#local-mutebtn').on('click',()=>{
        if($('#local-mutebtn').text()==='Mute'){
            localStream.getTracks().forEach(track=>track.enabled=false);
            $('#local-mutebtn').text('Unmute');
        }else{
            localStream.getTracks().forEach(track=>track.enabled=true);
            $('#local-mutebtn').text('Mute');
        }
    });

    let connect=_room=>{
        _room.on('open',()=>{
            _room.send(userdata);
        });
        _room.on('stream',stream=>{
            console.log(stream);
            addChatUserElm(stream.peerId);
            _room.send(userdata);
            remoteStreams[stream.peerId]=stream;
            $(`#${stream.peerId}-video`).get(0).srcObject=stream;
            $(`#${stream.peerId}-video`).get(0).play();
        })
        _room.on('data',msg=>{
            console.log(msg);
            if(msg.data.username){
                usersdata[msg.src]={
                    username:msg.data.username,
                    usericon:msg.data.usericon
                };
                $(`#${msg.src}-name`).text(msg.data.username);
                if(msg.data.usericon){
                    setTimeout(()=>{
                        const dataView = new Uint8Array(msg.data.usericon);
                        const dataBlob = new Blob([dataView]);
                        const url = URL.createObjectURL(dataBlob);
                        $(`#${msg.src}-icon`).attr('src',url);
                    },500);
                }
            }
        });
        _room.on('peerJoin',id=>{
            console.log(id);
        });
        _room.on('peerLeave',id=>{
            console.log(id);
            remoteStreams[id]=null;
            usersdata[id]=null;
            removeChatUserElm(id);
        });
    };
    let addChatUserElm=(id)=>{
        let _elm=`

${(usersdata[id]?usersdata[id].username:id)}

            <video id="${id}-video" autoplay></video>

                <button id="${id}-mutebtn" class="btn btn-secondary">Mute</button>

`;

        $('#chat-users').append(_elm);

        $(`#${id}-mutebtn`).on('click',()=>{
            if($(`#${id}-mutebtn`).text()==='Mute'){
                remoteStreams[id].getTracks().forEach(track=>track.enabled=false);
                $(`#${id}-mutebtn`).text('Unmute');
                $(`#${id}`).removeClass('active-user');
                $(`#${id}`).addClass('mute-user');
            }else{
                remoteStreams[id].getTracks().forEach(track=>track.enabled=true);
                $(`#${id}-mutebtn`).text('Mute');
                $(`#${id}`).removeClass('mute-user');
                $(`#${id}`).addClass('active-user');
            }
        })
    };

    let removeChatUserElm=(id)=>{
        $(`#${id}`).remove();
    }

    let removeChatUserElms=()=>{
        let elms=$('.chat-user');
        for(let i=0;i<elms.length;i++){
            if(elms[i].className.indexOf('local-user')===-1){
                elms[i].remove();
            }
        }
    };
});<|endoftext|>


<commit_before>var controlMapEl = $('#control_map');
var uploadBtn = $('#upload_button');
var addMissionTakeoffBtn = $('#add_mission_takeoff');
var addMissionRtlBtn = $('#add_mission_rtl');
var takeOffAltEl = $('#takeoff_altitude');
var clearMissions = $('#clear_missions');
var pathPointsContainter = $('#path_points_tab');
var logsContainer = $('#logs_tab');
var logsInner = $('#logs_tab .logs_tab_inner');
var logsEl = $('[data-field=logs]');
var clearLogsBtn = $('#clear_logs');

var pointMovingArrows = $('#point_moving_arrows_template');
pointMovingArrows.remove();

window.missions = [];
var droneMarker;

changeButtons(connected, armed);
var droneLatLng = L.latLng(droneLat, droneLng);
droneLatLng.name = 'drone';

// Create map
controlMapEl.on('contextmenu', event => event.preventDefault());
var controlMap = L.map('control_map').setView([droneLat, droneLng], 17);

L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
	maxZoom: 20,
	subdomains:['mt0','mt1','mt2','mt3']
}).addTo(controlMap);

droneMarker = L.circle([droneLat, droneLng], {
	color: '#F44336',
	fillColor: '#F44336',
	fillOpacity: 1,
	radius: 1.7
}).addTo(controlMap);

// On map click add new point
var popup = L.popup();

controlMap.on('click', function(e){
	popup
        .setLatLng(e.latlng)
        .setContent("<form id='alt-map'> ROI:  <input id='roi_switch' type='checkbox'>

 <input type='number' id='alt' class='form-control' style='border: 1px dashed black !important; width: 200px' placeholder='Choose altitude' /></form>")
        .openOn(controlMap);

	$('#alt').focus();
	window.latlng = e.latlng;

	$("#alt-map").submit(function(e){
		e.preventDefault();
		var point = window.latlng;
		var alt = $("#alt").val();
		if(alt == '')
			point.alt = 5;
		else
			point.alt = alt;
		var roi = $("#roi_switch").is(":checked");
		if(roi == true){
			point.name = 'roi';
			//Add a different marker
			addLog('ROI mission added');
		} else{
			point.name = 'fly_to';
			addPointToPath(point);
			addLog('Fly to location mission added;');
		}
		console.log(roi);
		controlMap.closePopup();
	});
});

var path = L.polyline([]).addTo(controlMap);
var pathPoints=false, pathPointsCircle=[];
var lastPoint, rtlLine=false;
var pointsCircles = [];

pathPointsContainter.text('');
pathPointsContainter.append('
');
pathPointsContainter.find('ul').append('
 Launches from ('+ droneLat +', '+ droneLat +')
');

uploadBtn.on('click', function(){
	upload();
	addLog('Missions uploaded to the server;');
});

addMissionTakeoffBtn.on('click', function(){
	var takeOffAlt = 0;
	if( takeOffAltEl.val() == '' )
		takeOffAlt = 5;
	else
		takeOffAlt = takeOffAltEl.val();

	window.missions.push({
		name: 'takeoff',
		alt: Number(takeOffAlt),
	});

	updatePath();
	takeOffAltEl.val('');
	addLog('Take off mission added;');
});

// TODO: change to armedLocation
addMissionRtlBtn.on('click', function(){
	var rtlId = makeid();
	window.missions.push({
		id: rtlId,
		lat: droneLat,
		lng: droneLng,
		name: 'rtl'
	});

	var rtlObj = L.latLng(droneLat, droneLng);
	rtlObj.name = 'rtl';
	rtlObj.id = rtlId;

	if(pathPoints != false)
		pathPoints.push( rtlObj );
	else {
		pathPoints = [];
		pathPoints.push( rtlObj );
	}
	updatePath();
	addLog('Return to launch mission added;');
});

$('#add_mission_change_alt').on('click', function(){
	var alt = $('#change_altitude').val();

	if(isNaN(alt) || alt == '')
		alt = 5;

	window.missions.push({
		name: 'change_alt',
		alt: alt
	});
	updatePath();
	$('#change_altitude').val('');
	addLog('Change altitude mission added;');
});

$('#mission_land').on('click', function(){
	window.missions.push({
		name: 'land'
	});
	updatePath();
	addLog('Land mission added;');
});

clearMissions.on('click', function(){
	socket.emit('clear_missions');
	pathPoints = false;
	window.missions = [];
	updatePath();
	addLog('Clearing all the missions;');
});

clearLogsBtn.on('click', function(){
	logsEl.html('');
	firstLog = true;
});

// ----- DIRECT -----

$(document).on("click", "#force_land", function(event){
	socket.emit('force_land');
	iziToast.show({
    	title: 'FORCE_LAND was emmited to the server!',
		color: 'green'
	});
	addLog('Doing FORCE_LAND;');
});

$(document).on("click", "#force_rtl", function(event){
	socket.emit('force_rtl');
	iziToast.show({
    	title: 'FORCE_RTL was emmited to the server!',
		color: 'green'
	});
	addLog('Doing FORCE_RTL;');
});

$(document).on("click", "#force_auto_mode", function(event){
	socket.emit('vehicle_auto');
	iziToast.show({
    	title: 'VEHICLE_AUTO was emmited to the server!',
		color: 'green'
	});
	addLog('Doing VEHICLE_AUTO;');
});

$(document).on("click", "#force_guided_mode", function(event){
	socket.emit('vehicle_guided');
	iziToast.show({
    	title: 'VEHICLE_GUIDED was emmited to the server!',
		color: 'green'
	});
	addLog('Doing VEHICLE_GUIDED;');
});

$(document).on("click", "#force_loiter", function(event){
	socket.emit('force_loiter');
	iziToast.show({
    	title: 'FORCE_LOITER was emmited to the server!',
		color: 'green'
	});
	addLog('Doing FORCE_LOITER;');
});

$(document).on("click", "#connect", function(event){
	if(connected){
		socket.emit('vehicle_disconnect');
		iziToast.show({
			title: 'Disconecting from Vehicle!',
			color: 'red'
		});
		addLog('Disconnecting from Vehicle;');
	} else {
		socket.emit('vehicle_connect');
		iziToast.show({
			title: 'Connecting to Vehicle!',
			color: 'yellow'
		});
		addLog('Connecting to Vehicle;');
	}
});

$(document).on("click", "#arm", function(event){
	if(armed){
		socket.emit('disarm');
		iziToast.show({
			title: 'Disarming the vehicle!',
			color: 'red'
		});
		addLog('Disarming;');
	} else {
		socket.emit('arm');
		iziToast.show({
			title: 'Arming the vehicle!',
			color: 'yellow'
		});
		addLog('Arming;');
	}
});

// ----- END -----

$("#modal").iziModal({
	title: 'Advanced options',
	headerColor: '#263238',
	width: '644px'
});

$('#settings').on('click', function(e){
	e.preventDefault();
	$('#modal').iziModal('open', this);
});

$('#update_settings').on('click', function(e){
	var settings = [];
	var settingsInputs = $('#settings .setting');
	$.each(settingsInputs, function(i, value){
		if( $(value).attr('val-type') == 'number' ){
			settings.push({
				name: $(value).attr('setting-name'),
				value: Number($(value).find('input').val()),
				type: $(value).attr('val-type')
			});
		}else if( $(value).attr('val-type') == 'string' ){
			settings.push({
				name: $(value).attr('setting-name'),
				value: $(value).find('input').val(),
				type: $(value).attr('val-type')
			});
		}else if( $(value).attr('val-type') == 'bool' ){
			settings.push({
				name: $(value).attr('setting-name'),
				value: ( $(value).find('input[name^=radio]:checked').val() == 'True' ),
				type: $(value).attr('val-type')
			});
		}
	});
	updateSettings( settings );
});

// Stream iframe height
$('.stream-iframe').height( $('.stream-container').height() );<commit_msg>ROI point marker<commit_after>var controlMapEl = $('#control_map');
var uploadBtn = $('#upload_button');
var addMissionTakeoffBtn = $('#add_mission_takeoff');
var addMissionRtlBtn = $('#add_mission_rtl');
var takeOffAltEl = $('#takeoff_altitude');
var clearMissions = $('#clear_missions');
var pathPointsContainter = $('#path_points_tab');
var logsContainer = $('#logs_tab');
var logsInner = $('#logs_tab .logs_tab_inner');
var logsEl = $('[data-field=logs]');
var clearLogsBtn = $('#clear_logs');

var pointMovingArrows = $('#point_moving_arrows_template');
pointMovingArrows.remove();

window.missions = [];
var droneMarker;

changeButtons(connected, armed);
var droneLatLng = L.latLng(droneLat, droneLng);
droneLatLng.name = 'drone';

// Create map
controlMapEl.on('contextmenu', event => event.preventDefault());
var controlMap = L.map('control_map').setView([droneLat, droneLng], 17);

L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
	maxZoom: 20,
	subdomains:['mt0','mt1','mt2','mt3']
}).addTo(controlMap);

droneMarker = L.circle([droneLat, droneLng], {
	color: '#F44336',
	fillColor: '#F44336',
	fillOpacity: 1,
	radius: 1.7
}).addTo(controlMap);

// On map click add new point
var popup = L.popup();

controlMap.on('click', function(e){
	popup
        .setLatLng(e.latlng)
        .setContent("<form id='alt-map'> ROI:  <input id='roi_switch' type='checkbox'>

 <input type='number' id='alt' class='form-control' style='border: 1px dashed black !important; width: 200px' placeholder='Choose altitude' /></form>")
        .openOn(controlMap);

	$('#alt').focus();
	window.latlng = e.latlng;

	$("#alt-map").submit(function(e){
		e.preventDefault();
		var point = window.latlng;
		var alt = $("#alt").val();
		if(alt == '')
			point.alt = 5;
		else
			point.alt = alt;
		var roi = $("#roi_switch").is(":checked");
		if(roi == true){
			point.name = 'roi';

			L.circle(point, {
				color: 'green',
				fillColor: 'green',
				fillOpacity: 1,
				radius: 2
			}).addTo(controlMap).bringToBack();

			addLog('ROI mission added');
		} else{
			point.name = 'fly_to';
			addPointToPath(point);
			addLog('Fly to location mission added;');
		}
		console.log(roi);
		controlMap.closePopup();
	});
});

var path = L.polyline([]).addTo(controlMap);
var pathPoints=false, pathPointsCircle=[];
var lastPoint, rtlLine=false;
var pointsCircles = [];

pathPointsContainter.text('');
pathPointsContainter.append('
');
pathPointsContainter.find('ul').append('
 Launches from ('+ droneLat +', '+ droneLat +')
');

uploadBtn.on('click', function(){
	upload();
	addLog('Missions uploaded to the server;');
});

addMissionTakeoffBtn.on('click', function(){
	var takeOffAlt = 0;
	if( takeOffAltEl.val() == '' )
		takeOffAlt = 5;
	else
		takeOffAlt = takeOffAltEl.val();

	window.missions.push({
		name: 'takeoff',
		alt: Number(takeOffAlt),
	});

	updatePath();
	takeOffAltEl.val('');
	addLog('Take off mission added;');
});

// TODO: change to armedLocation
addMissionRtlBtn.on('click', function(){
	var rtlId = makeid();
	window.missions.push({
		id: rtlId,
		lat: droneLat,
		lng: droneLng,
		name: 'rtl'
	});

	var rtlObj = L.latLng(droneLat, droneLng);
	rtlObj.name = 'rtl';
	rtlObj.id = rtlId;

	if(pathPoints != false)
		pathPoints.push( rtlObj );
	else {
		pathPoints = [];
		pathPoints.push( rtlObj );
	}
	updatePath();
	addLog('Return to launch mission added;');
});

$('#add_mission_change_alt').on('click', function(){
	var alt = $('#change_altitude').val();

	if(isNaN(alt) || alt == '')
		alt = 5;

	window.missions.push({
		name: 'change_alt',
		alt: alt
	});
	updatePath();
	$('#change_altitude').val('');
	addLog('Change altitude mission added;');
});

$('#mission_land').on('click', function(){
	window.missions.push({
		name: 'land'
	});
	updatePath();
	addLog('Land mission added;');
});

clearMissions.on('click', function(){
	socket.emit('clear_missions');
	pathPoints = false;
	window.missions = [];
	updatePath();
	addLog('Clearing all the missions;');
});

clearLogsBtn.on('click', function(){
	logsEl.html('');
	firstLog = true;
});

// ----- DIRECT -----

$(document).on("click", "#force_land", function(event){
	socket.emit('force_land');
	iziToast.show({
    	title: 'FORCE_LAND was emmited to the server!',
		color: 'green'
	});
	addLog('Doing FORCE_LAND;');
});

$(document).on("click", "#force_rtl", function(event){
	socket.emit('force_rtl');
	iziToast.show({
    	title: 'FORCE_RTL was emmited to the server!',
		color: 'green'
	});
	addLog('Doing FORCE_RTL;');
});

$(document).on("click", "#force_auto_mode", function(event){
	socket.emit('vehicle_auto');
	iziToast.show({
    	title: 'VEHICLE_AUTO was emmited to the server!',
		color: 'green'
	});
	addLog('Doing VEHICLE_AUTO;');
});

$(document).on("click", "#force_guided_mode", function(event){
	socket.emit('vehicle_guided');
	iziToast.show({
    	title: 'VEHICLE_GUIDED was emmited to the server!',
		color: 'green'
	});
	addLog('Doing VEHICLE_GUIDED;');
});

$(document).on("click", "#force_loiter", function(event){
	socket.emit('force_loiter');
	iziToast.show({
    	title: 'FORCE_LOITER was emmited to the server!',
		color: 'green'
	});
	addLog('Doing FORCE_LOITER;');
});

$(document).on("click", "#connect", function(event){
	if(connected){
		socket.emit('vehicle_disconnect');
		iziToast.show({
			title: 'Disconecting from Vehicle!',
			color: 'red'
		});
		addLog('Disconnecting from Vehicle;');
	} else {
		socket.emit('vehicle_connect');
		iziToast.show({
			title: 'Connecting to Vehicle!',
			color: 'yellow'
		});
		addLog('Connecting to Vehicle;');
	}
});

$(document).on("click", "#arm", function(event){
	if(armed){
		socket.emit('disarm');
		iziToast.show({
			title: 'Disarming the vehicle!',
			color: 'red'
		});
		addLog('Disarming;');
	} else {
		socket.emit('arm');
		iziToast.show({
			title: 'Arming the vehicle!',
			color: 'yellow'
		});
		addLog('Arming;');
	}
});

// ----- END -----

$("#modal").iziModal({
	title: 'Advanced options',
	headerColor: '#263238',
	width: '644px'
});

$('#settings').on('click', function(e){
	e.preventDefault();
	$('#modal').iziModal('open', this);
});

$('#update_settings').on('click', function(e){
	var settings = [];
	var settingsInputs = $('#settings .setting');
	$.each(settingsInputs, function(i, value){
		if( $(value).attr('val-type') == 'number' ){
			settings.push({
				name: $(value).attr('setting-name'),
				value: Number($(value).find('input').val()),
				type: $(value).attr('val-type')
			});
		}else if( $(value).attr('val-type') == 'string' ){
			settings.push({
				name: $(value).attr('setting-name'),
				value: $(value).find('input').val(),
				type: $(value).attr('val-type')
			});
		}else if( $(value).attr('val-type') == 'bool' ){
			settings.push({
				name: $(value).attr('setting-name'),
				value: ( $(value).find('input[name^=radio]:checked').val() == 'True' ),
				type: $(value).attr('val-type')
			});
		}
	});
	updateSettings( settings );
});

// Stream iframe height
$('.stream-iframe').height( $('.stream-container').height() );<|endoftext|>


<commit_before>
// Check for WebGL
if ( !Detector.webgl ) {

    Detector.addGetWebGLMessage();

}

// Application parameters
var maxVertices = 120000;
var maxTriangleSideSize = 0.3;
var editInfluenceRadius = 0.4;

// Global variables
var renderer = null;
var theCanvas = null;
var camera = null;
var scene = null;

var material = null;
var subdividibleMesh = null;
var outputMesh = null;

var canEdit = true;
var initialCursorPosition = new THREE.Vector3();
var initialCursorNormal = new THREE.Vector3();
var currentCursorPosition = new THREE.Vector3();
var currentCursorIncrement = new THREE.Vector3();
var previousShadingMode = THREE.SmoothShading;
var mouseStatus = 0;
var raycaster = new THREE.Raycaster();
var mouseCoords = new THREE.Vector2();
var plane = new THREE.Plane();
var line = new THREE.Line3();
var ballHelper = null;
var numFramesToShowBallHelper = 0;

var tempVector1 = new THREE.Vector3();
var tempVector2 = new THREE.Vector3();

// Main code

init();
run();

// Functions

function init() {

    camera = new THREE.PerspectiveCamera( 45, 1, 0.01, 100 );
    camera.position.set( 2, 2, 5 );

    scene = new THREE.Scene();

    createLights();

    material = createMaterial( 0xFFA030 );

    createSubdivisibleMesh();

    var ballMat = createMaterial( 0x00A030 );
    ballMat.transparent = true;
    ballMat.opacity = 0.5;
    ballHelper = new THREE.Mesh( new THREE.SphereBufferGeometry( 1, 30, 20 ), ballMat );
    ballHelper.scale.setScalar( editInfluenceRadius );
    ballHelper.visible = false;
    scene.add( ballHelper );

    // Renderer
    renderer = new THREE.WebGLRenderer( {
        antialias: true
    } );
    renderer.setClearColor( 0x000000 );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.shadowMap.enabled = true;
    theCanvas = renderer.domElement;

    // Gets HTML elements
    div3DView = document.getElementById( "idDiv3DView" );

    // Inserts the canvas in its place
    div3DView.appendChild( theCanvas );

    controls = new THREE.OrbitControls( camera );

    attachEvents();

}

function attachEvents() {

    window.addEventListener( 'keydown', onKeyDown, false );

    window.addEventListener( 'mousedown', onMouseDown, false );
    window.addEventListener( 'mousemove', onMouseMove, false );
    window.addEventListener( 'mouseup', onMouseUp, false );
    window.addEventListener( 'mousewheel', onMouseWheel, false );
    window.addEventListener( 'touchstart', onTouchStart, false );
    window.addEventListener( 'touchend', onTouchEnd, false );
    window.addEventListener( 'touchmove', onTouchMove, false );

    window.addEventListener( 'resize', onWindowResize, false );

    onWindowResize();

}

function onWindowResize() {

    var view3DResolutionX = window.innerWidth;
    var view3DResolutionY = window.innerHeight;
    var view3DAspect = view3DResolutionX / view3DResolutionY;

    camera.aspect = view3DAspect;
    camera.updateProjectionMatrix();

    renderer.setSize( view3DResolutionX, view3DResolutionY );

    renderer.setSize( view3DResolutionX, view3DResolutionY );
}

function onKeyDown( event ) {

    switch ( event.keyCode ) {

        // "W" key switches wireframe mode
        case 87:
            material.wireframe = ! material.wireframe;
            if ( material.wireframe ) {
                material.shading = THREE.SmoothShading;
            }
            else {
                material.shading = previousShadingMode;
            }

            material.needsUpdate = true;
            break;

        // "S" key switches shading mode
        case 83:

            if ( ! material.wireframe ) {
                if ( material.shading === THREE.SmoothShading ) {
                    material.shading = THREE.FlatShading;
                    previousShadingMode = THREE.FlatShading;
                }
                else {
                    material.shading = THREE.SmoothShading;
                    previousShadingMode = THREE.SmoothShading;
                }
            }

            material.needsUpdate = true;
            break;

    }

}

function onMouseDown( event ) {

    handleMouseDown( event.clientX, event.clientY, event.ctrlKey );

}

function handleMouseDown( clientX, clientY, ctrlKey ) {

    mouseStatus = 0;

    if ( ctrlKey ) {
        return;
    }

    mouseStatus = 1;

    mouseCoords.set( ( clientX / window.innerWidth ) * 2 - 1, - ( clientY / window.innerHeight ) * 2 + 1 );
    raycaster.setFromCamera( mouseCoords, camera );
    var intersects = this.raycaster.intersectObject( outputMesh );

    if ( intersects.length > 0 ) {

        var intersection = intersects[ 0 ];

        initialCursorPosition.copy( intersection.point );

        var obj = intersection.object;

        // Obtain normal in world space
        if ( intersection.face && obj ) {
            initialCursorNormal.copy( intersection.face.normal ).transformDirection( obj.matrixWorld );
        }
        else {
            initialCursorNormal.set( 0, 1, 0 );
        }

        // Builds plane where the cursor will move until mouse button is released
        tempVector1.crossVectors( raycaster.ray.direction, initialCursorNormal );
        tempVector2.crossVectors( tempVector1, initialCursorNormal );
        tempVector2.normalize();
        plane.setFromNormalAndCoplanarPoint( tempVector2, initialCursorPosition );

        // Set visual helper position
        ballHelper.position.copy( initialCursorPosition );

        currentCursorPosition.copy( initialCursorPosition );
        currentCursorIncrement.set( 0, 0, 0 );

    }
    else {

        mouseStatus = 0;

    }

}

function onMouseMove( event ) {

    handleMouseMove( event.clientX, event.clientY, event.ctrlKey );

}

function handleMouseMove( clientX, clientY, ctrlKey ) {

    if ( ctrlKey ) {
        mouseStatus = 0;
        return;
    }

    if ( mouseStatus === 0 ) {
        return;
    }

    mouseCoords.set( ( clientX / window.innerWidth ) * 2 - 1, - ( clientY / window.innerHeight ) * 2 + 1 );
    raycaster.setFromCamera( mouseCoords, camera );
    line.start.copy( raycaster.ray.origin );
    line.end.copy( raycaster.ray.direction );
    line.end.multiplyScalar( 100 );
    line.end.add( raycaster.ray.origin );

    var pointResult = plane.intersectLine( line, tempVector1 );
    if ( pointResult !== undefined ) {

        currentCursorIncrement.subVectors( pointResult, currentCursorPosition );
        currentCursorPosition.copy( pointResult );

        ballHelper.position.copy( pointResult );

        editMesh();

    }

}

function onMouseUp( event ) {

    mouseStatus = 0;

}

function onMouseWheel( event ) {

    // The wheel changes influence radius

    var delta = 0;

    if ( event.wheelDelta !== undefined ) {

            // WebKit / Opera / Explorer 9

            delta = event.wheelDelta;

    } else if ( event.detail !== undefined ) {

            // Firefox

            delta = - event.detail;

    }

    editInfluenceRadius += Math.sign( delta ) * 0.1;
    ballHelper.scale.setScalar( editInfluenceRadius );
    numFramesToShowBallHelper = 30;
}

function onTouchStart( event ) {

    if ( event.touches.length !== 1 ) {
        return;
    }

    var touch = event.touches[ 0 ];

    handleMouseDown( touch.clientX, touch.clientY, false );

}

function onTouchMove( event ) {

    if ( event.touches.length !== 1 ) {
        return;
    }

    var touch = event.touches[ 0 ];

    handleMouseMove( touch.clientX, touch.clientY, false );

}

function onTouchEnd( event ) {

    onMouseUp();

}

function createMaterial( color ) {

    return new THREE.MeshStandardMaterial( {
        // 0xRRGGBB
        color: color,
        // > 0
        roughness: 0.2,
        // > 0
        metalness: 0.1,
        // 0xRRGGBB
        emissive: 0,
        // > 0
        emissiveIntensity: 0,
        // 0..1
        envMapIntensity: 0,
        // 0 (transparent) to 1 (opaque)
        opacity: 1,
        transparent: false,
        // > 0
        refractionRatio: 1,
        // true or false
        shading: THREE.SmoothShading,
        // true or false
        wireframe: false,
        wireframeLinewidth: 2
    } );

}

function createLights() {

    scene.add( new THREE.AmbientLight( 0x808080, 1 ) );

    function createLight( pos, color, intensity ) {

        var sun = new THREE.DirectionalLight( color, intensity );

        sun.position.copy( pos );

        sun.castShadow = true;

        var d = 20;
        var s = 10;
        sun.shadow.camera.left = - s;
        sun.shadow.camera.right = s;
        sun.shadow.camera.top = s;
        sun.shadow.camera.bottom = - s;

        sun.shadow.camera.near = d / 30;
        sun.shadow.camera.far = d;

        sun.shadow.mapSize.x = 1024 * 2;
        sun.shadow.mapSize.y = 1024 * 2;

        scene.add( sun );

    }

    createLight( new THREE.Vector3( 5, 8, 3 ), 0xFFFFFF, 1 );
    createLight( new THREE.Vector3( -5, -4, -1 ), 0xFFA0A0, 0.2 );
}

function createSubdivisibleMesh() {

    outputMesh = SubdivisibleMesh.createOutputMesh( maxVertices, material );
    outputMesh.castShadow = true;
    outputMesh.receiveShadow = true;
    scene.add( outputMesh );

    var bl = 1;
    var g = new THREE.BoxGeometry( bl, bl, bl, 1, 1, 1 );
    //var g = new THREE.SphereBufferGeometry( 1, 12, 12 );
    //var g = new THREE.TetrahedronGeometry( 1, 0 );

    subdividibleMesh = new SubdivisibleMesh();

    subdividibleMesh.mergeInputGeometry( g );

    var subdivided = 1;
    while ( subdivided  > 0 ) {
        subdivided = subdividibleMesh.subdivide( maxTriangleSideSize, maxVertices );
    }

    subdividibleMesh.computeNormals();
    subdividibleMesh.fillMesh( outputMesh );

}

function growCoral() {

    subdividibleMesh.applyScalarFieldToVertices( field1, 0.05 / 60 );
//    subdividibleMesh.applyScalarFieldToVertices( field1, 0.05 );
//    subdividibleMesh.applyVectorFieldToVertices( field2, 0.05 );

    subdividibleMesh.subdivide( maxTriangleSideSize, maxVertices );

    subdividibleMesh.computeNormals();

    subdividibleMesh.fillMesh( outputMesh );

}

function editMesh() {

    if ( ! canEdit ) {
        return;
    }

    subdividibleMesh.applyVectorFieldToVertices( userVectorField, 1 );

    subdividibleMesh.subdivide( maxTriangleSideSize, maxVertices );

    subdividibleMesh.computeNormals();

    if ( subdividibleMesh.fillMesh( outputMesh ) ) {
        // Max number of vertices reached, can't edit the mesh anymore
        canEdit = false;
        ballHelper.material.color = new THREE.Color( 0xFF0000 );
        ballHelper.material.opacity = 1;
        ballHelper.material.needsUpdate = true;
    }

}

function field1( position, normal ) {

    var d = Math.sqrt( position.x * position.x + position.z * position.z );

    if ( d <= 0.4 && position.y > 0 ) {
        return Math.max( 0, normal.y );
    }

    return 0;

}

var field2 = function() {

    var v = new THREE.Vector3();

    return function( position ) {

        var d = Math.sqrt( position.x * position.x + position.z * position.z );
        var amount = 0;
        if ( d <= 0.4 && position.y > 0 ) {
            amount = 1;
        }

        v.set( 0, amount, 0 );

        return v;
    };

}();

var userVectorField = function() {

    var v = new THREE.Vector3();
    var v1 = new THREE.Vector3();
    var v2 = new THREE.Vector3();
    var vField = new THREE.Vector3();

    return function( position, normal ) {

        v.subVectors( position, currentCursorPosition );

        var distance = v.length();
        var amount = 0;
        vField.set( 0, 0, 0 );

        if ( distance < editInfluenceRadius ) {

            amount = 1 - distance / editInfluenceRadius;

            vField.copy( currentCursorIncrement );
            vField.multiplyScalar( amount );

            var angle = amount * Math.PI * 0.5;
            var amount6 = editInfluenceRadius * amount / 6;

            v1.copy( normal ).multiplyScalar( Math.sin( angle ) * amount6 );
            v2.copy( v ).normalize().multiplyScalar( Math.cos( angle ) * amount6 );

            vField.add( v1 );
            vField.add( v2 );

        }

        return vField;
    };

}();

function getTime() {
    return performance.now() / 1000;
}

function run() {

    requestAnimationFrame( run );

    controls.update();

//    growCoral();

    ballHelper.visible = mouseStatus === 1 || numFramesToShowBallHelper > 0;

    if ( numFramesToShowBallHelper > 0 ) {
        numFramesToShowBallHelper--;
    }

    renderer.render( scene, camera );

}
<commit_msg>Adding support for mobile, second attempt<commit_after>
// Check for WebGL
if ( !Detector.webgl ) {

    Detector.addGetWebGLMessage();

}

// Application parameters
var maxVertices = 120000;
var maxTriangleSideSize = 0.3;
var editInfluenceRadius = 0.4;

// Global variables
var renderer = null;
var theCanvas = null;
var camera = null;
var scene = null;

var material = null;
var subdividibleMesh = null;
var outputMesh = null;

var canEdit = true;
var pressedAtLeastOnce = false;
var initialCursorPosition = new THREE.Vector3();
var initialCursorNormal = new THREE.Vector3();
var currentCursorPosition = new THREE.Vector3();
var currentCursorIncrement = new THREE.Vector3();
var previousShadingMode = THREE.SmoothShading;
var mouseStatus = 0;
var raycaster = new THREE.Raycaster();
var mouseCoords = new THREE.Vector2();
var plane = new THREE.Plane();
var line = new THREE.Line3();
var ballHelper = null;
var numFramesToShowBallHelper = 0;

var tempVector1 = new THREE.Vector3();
var tempVector2 = new THREE.Vector3();

// Main code

init();
run();

// Functions

function init() {

    camera = new THREE.PerspectiveCamera( 45, 1, 0.01, 100 );
    camera.position.set( 2, 2, 5 );

    scene = new THREE.Scene();

    createLights();

    material = createMaterial( 0xFFA030 );

    createSubdivisibleMesh();

    var ballMat = createMaterial( 0x00A030 );
    ballMat.transparent = true;
    ballMat.opacity = 0.5;
    ballHelper = new THREE.Mesh( new THREE.SphereBufferGeometry( 1, 30, 20 ), ballMat );
    ballHelper.scale.setScalar( editInfluenceRadius );
    ballHelper.visible = false;
    scene.add( ballHelper );

    // Renderer
    renderer = new THREE.WebGLRenderer( {
        antialias: true
    } );
    renderer.setClearColor( 0x000000 );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.shadowMap.enabled = true;
    theCanvas = renderer.domElement;

    // Gets HTML elements
    div3DView = document.getElementById( "idDiv3DView" );

    // Inserts the canvas in its place
    div3DView.appendChild( theCanvas );

    controls = new THREE.OrbitControls( camera );

    attachEvents();

}

function attachEvents() {

    window.addEventListener( 'keydown', onKeyDown, false );

    window.addEventListener( 'mousedown', onMouseDown, false );
    window.addEventListener( 'mousemove', onMouseMove, false );
    window.addEventListener( 'mouseup', onMouseUp, false );
    window.addEventListener( 'mousewheel', onMouseWheel, false );
    window.addEventListener( 'touchstart', onTouchStart, false );
    window.addEventListener( 'touchend', onTouchEnd, false );
    window.addEventListener( 'touchmove', onTouchMove, false );

    window.addEventListener( 'resize', onWindowResize, false );

    onWindowResize();

}

function onWindowResize() {

    var view3DResolutionX = window.innerWidth;
    var view3DResolutionY = window.innerHeight;
    var view3DAspect = view3DResolutionX / view3DResolutionY;

    camera.aspect = view3DAspect;
    camera.updateProjectionMatrix();

    renderer.setSize( view3DResolutionX, view3DResolutionY );

    renderer.setSize( view3DResolutionX, view3DResolutionY );
}

function fullScreenizeElement( elem ) {

    if ( elem.requestFullscreen ) {

        elem.requestFullscreen();

    } else if ( elem.msRequestFullscreen ) {

        elem.msRequestFullscreen();

    } else if ( elem.mozRequestFullScreen ) {

        elem.mozRequestFullScreen();

    } else if ( elem.webkitRequestFullscreen ) {

        elem.webkitRequestFullscreen();

    }

}

function onKeyDown( event ) {

    switch ( event.keyCode ) {

        // "W" key switches wireframe mode
        case 87:
            material.wireframe = ! material.wireframe;
            if ( material.wireframe ) {
                material.shading = THREE.SmoothShading;
            }
            else {
                material.shading = previousShadingMode;
            }

            material.needsUpdate = true;
            break;

        // "S" key switches shading mode
        case 83:

            if ( ! material.wireframe ) {
                if ( material.shading === THREE.SmoothShading ) {
                    material.shading = THREE.FlatShading;
                    previousShadingMode = THREE.FlatShading;
                }
                else {
                    material.shading = THREE.SmoothShading;
                    previousShadingMode = THREE.SmoothShading;
                }
            }

            material.needsUpdate = true;
            break;

    }

}

function onMouseDown( event ) {

    handleMouseDown( event.clientX, event.clientY, event.ctrlKey );

}

function handleMouseDown( clientX, clientY, ctrlKey ) {

    mouseStatus = 0;

    if ( ctrlKey ) {
        return;
    }

    if ( ! pressedAtLeastOnce ) {
        console.log( "AMEM" );
        fullScreenizeElement( div3DView );
        pressedAtLeastOnce = true;
    }

    mouseStatus = 1;

    mouseCoords.set( ( clientX / window.innerWidth ) * 2 - 1, - ( clientY / window.innerHeight ) * 2 + 1 );
    raycaster.setFromCamera( mouseCoords, camera );
    var intersects = this.raycaster.intersectObject( outputMesh );

    if ( intersects.length > 0 ) {

        var intersection = intersects[ 0 ];

        initialCursorPosition.copy( intersection.point );

        var obj = intersection.object;

        // Obtain normal in world space
        if ( intersection.face && obj ) {
            initialCursorNormal.copy( intersection.face.normal ).transformDirection( obj.matrixWorld );
        }
        else {
            initialCursorNormal.set( 0, 1, 0 );
        }

        // Builds plane where the cursor will move until mouse button is released
        tempVector1.crossVectors( raycaster.ray.direction, initialCursorNormal );
        tempVector2.crossVectors( tempVector1, initialCursorNormal );
        tempVector2.normalize();
        plane.setFromNormalAndCoplanarPoint( tempVector2, initialCursorPosition );

        // Set visual helper position
        ballHelper.position.copy( initialCursorPosition );

        currentCursorPosition.copy( initialCursorPosition );
        currentCursorIncrement.set( 0, 0, 0 );

    }
    else {

        mouseStatus = 0;

    }

}

function onMouseMove( event ) {

    handleMouseMove( event.clientX, event.clientY, event.ctrlKey );

}

function handleMouseMove( clientX, clientY, ctrlKey ) {

    if ( ctrlKey ) {
        mouseStatus = 0;
        return;
    }

    if ( mouseStatus === 0 ) {
        return;
    }

    mouseCoords.set( ( clientX / window.innerWidth ) * 2 - 1, - ( clientY / window.innerHeight ) * 2 + 1 );
    raycaster.setFromCamera( mouseCoords, camera );
    line.start.copy( raycaster.ray.origin );
    line.end.copy( raycaster.ray.direction );
    line.end.multiplyScalar( 100 );
    line.end.add( raycaster.ray.origin );

    var pointResult = plane.intersectLine( line, tempVector1 );
    if ( pointResult !== undefined ) {

        currentCursorIncrement.subVectors( pointResult, currentCursorPosition );
        currentCursorPosition.copy( pointResult );

        ballHelper.position.copy( pointResult );

        editMesh();

    }

}

function onMouseUp( event ) {

    mouseStatus = 0;

}

function onMouseWheel( event ) {

    // The wheel changes influence radius

    var delta = 0;

    if ( event.wheelDelta !== undefined ) {

            // WebKit / Opera / Explorer 9

            delta = event.wheelDelta;

    } else if ( event.detail !== undefined ) {

            // Firefox

            delta = - event.detail;

    }

    editInfluenceRadius += Math.sign( delta ) * 0.1;
    ballHelper.scale.setScalar( editInfluenceRadius );
    numFramesToShowBallHelper = 30;
}

function onTouchStart( event ) {

    if ( event.touches.length !== 1 ) {
        return;
    }

    var touch = event.touches[ 0 ];

    handleMouseDown( touch.clientX, touch.clientY, false );

}

function onTouchMove( event ) {

    if ( event.touches.length !== 1 ) {
        return;
    }

    var touch = event.touches[ 0 ];

    handleMouseMove( touch.clientX, touch.clientY, false );

}

function onTouchEnd( event ) {

    onMouseUp();

}

function createMaterial( color ) {

    return new THREE.MeshStandardMaterial( {
        // 0xRRGGBB
        color: color,
        // > 0
        roughness: 0.2,
        // > 0
        metalness: 0.1,
        // 0xRRGGBB
        emissive: 0,
        // > 0
        emissiveIntensity: 0,
        // 0..1
        envMapIntensity: 0,
        // 0 (transparent) to 1 (opaque)
        opacity: 1,
        transparent: false,
        // > 0
        refractionRatio: 1,
        // true or false
        shading: THREE.SmoothShading,
        // true or false
        wireframe: false,
        wireframeLinewidth: 2
    } );

}

function createLights() {

    scene.add( new THREE.AmbientLight( 0x808080, 1 ) );

    function createLight( pos, color, intensity ) {

        var sun = new THREE.DirectionalLight( color, intensity );

        sun.position.copy( pos );

        sun.castShadow = true;

        var d = 20;
        var s = 10;
        sun.shadow.camera.left = - s;
        sun.shadow.camera.right = s;
        sun.shadow.camera.top = s;
        sun.shadow.camera.bottom = - s;

        sun.shadow.camera.near = d / 30;
        sun.shadow.camera.far = d;

        sun.shadow.mapSize.x = 1024 * 2;
        sun.shadow.mapSize.y = 1024 * 2;

        scene.add( sun );

    }

    createLight( new THREE.Vector3( 5, 8, 3 ), 0xFFFFFF, 1 );
    createLight( new THREE.Vector3( -5, -4, -1 ), 0xFFA0A0, 0.2 );
}

function createSubdivisibleMesh() {

    outputMesh = SubdivisibleMesh.createOutputMesh( maxVertices, material );
    outputMesh.castShadow = true;
    outputMesh.receiveShadow = true;
    scene.add( outputMesh );

    var bl = 1;
    var g = new THREE.BoxGeometry( bl, bl, bl, 1, 1, 1 );
    //var g = new THREE.SphereBufferGeometry( 1, 12, 12 );
    //var g = new THREE.TetrahedronGeometry( 1, 0 );

    subdividibleMesh = new SubdivisibleMesh();

    subdividibleMesh.mergeInputGeometry( g );

    var subdivided = 1;
    while ( subdivided  > 0 ) {
        subdivided = subdividibleMesh.subdivide( maxTriangleSideSize, maxVertices );
    }

    subdividibleMesh.computeNormals();
    subdividibleMesh.fillMesh( outputMesh );

}

function growCoral() {

    subdividibleMesh.applyScalarFieldToVertices( field1, 0.05 / 60 );
//    subdividibleMesh.applyScalarFieldToVertices( field1, 0.05 );
//    subdividibleMesh.applyVectorFieldToVertices( field2, 0.05 );

    subdividibleMesh.subdivide( maxTriangleSideSize, maxVertices );

    subdividibleMesh.computeNormals();

    subdividibleMesh.fillMesh( outputMesh );

}

function editMesh() {

    if ( ! canEdit ) {
        return;
    }

    subdividibleMesh.applyVectorFieldToVertices( userVectorField, 1 );

    subdividibleMesh.subdivide( maxTriangleSideSize, maxVertices );

    subdividibleMesh.computeNormals();

    if ( subdividibleMesh.fillMesh( outputMesh ) ) {
        // Max number of vertices reached, can't edit the mesh anymore
        canEdit = false;
        ballHelper.material.color = new THREE.Color( 0xFF0000 );
        ballHelper.material.opacity = 1;
        ballHelper.material.needsUpdate = true;
    }

}

function field1( position, normal ) {

    var d = Math.sqrt( position.x * position.x + position.z * position.z );

    if ( d <= 0.4 && position.y > 0 ) {
        return Math.max( 0, normal.y );
    }

    return 0;

}

var field2 = function() {

    var v = new THREE.Vector3();

    return function( position ) {

        var d = Math.sqrt( position.x * position.x + position.z * position.z );
        var amount = 0;
        if ( d <= 0.4 && position.y > 0 ) {
            amount = 1;
        }

        v.set( 0, amount, 0 );

        return v;
    };

}();

var userVectorField = function() {

    var v = new THREE.Vector3();
    var v1 = new THREE.Vector3();
    var v2 = new THREE.Vector3();
    var vField = new THREE.Vector3();

    return function( position, normal ) {

        v.subVectors( position, currentCursorPosition );

        var distance = v.length();
        var amount = 0;
        vField.set( 0, 0, 0 );

        if ( distance < editInfluenceRadius ) {

            amount = 1 - distance / editInfluenceRadius;

            vField.copy( currentCursorIncrement );
            vField.multiplyScalar( amount );

            var angle = amount * Math.PI * 0.5;
            var amount6 = editInfluenceRadius * amount / 6;

            v1.copy( normal ).multiplyScalar( Math.sin( angle ) * amount6 );
            v2.copy( v ).normalize().multiplyScalar( Math.cos( angle ) * amount6 );

            vField.add( v1 );
            vField.add( v2 );

        }

        return vField;
    };

}();

function getTime() {
    return performance.now() / 1000;
}

function run() {

    requestAnimationFrame( run );

    controls.update();

//    growCoral();

    ballHelper.visible = mouseStatus === 1 || numFramesToShowBallHelper > 0;

    if ( numFramesToShowBallHelper > 0 ) {
        numFramesToShowBallHelper--;
    }

    renderer.render( scene, camera );

}
<|endoftext|>


<commit_before>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "http://localhost:4200?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;

}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info', 'fetched API Key ' + apiKey);
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      updateLoginDisplayElements(undefined);
      replaceALLApiKeyByStoredApiKey(undefined);
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {
  console.log('logout user');
  const oldApiKey = localStorage.getItem('APIKey');
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');
  updateLoginDisplayElements(undefined);
  replaceOldApiKeyByLoginLink(oldApiKey);
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

/**
 * copy the content of the element given in param
 *
 * @param {*} elementId id of the HTML element
 */
function copyToClipBoard(elementId) {
  var range = document.createRange();
  var copyText = document.getElementById(elementId);
  if (!copyText) {
    return;
  }
  range.selectNode(copyText);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("copy")
  selection.removeAllRanges();
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {
      $(this).html($(this).html().replace(/\$API_KEY/g,
        ""
        + "login to retrieve your api-key"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

function replaceOldApiKeyByLoginLink(oldApiKey) {
  if(oldApiKey){
    var re = new RegExp(oldApiKey , "g");
    $("body").children().each(function () {
      $(this).html($(this).html().replace(re,
        ""
        + "login to retrieve your api-key"));
  });
  }

}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

$(document).ready(function () {
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();
  console.log('apiKey', apiKey);
  console.log('email', email);

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<commit_msg>added reload window after logout<commit_after>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "http://localhost:4200?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;

}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info', 'fetched API Key ' + apiKey);
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      updateLoginDisplayElements(undefined);
      replaceALLApiKeyByStoredApiKey(undefined);
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {

  // remove api key and email from local storage
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');

  // reload page
  window.location.reload();
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

/**
 * copy the content of the element given in param
 *
 * @param {*} elementId id of the HTML element
 */
function copyToClipBoard(elementId) {
  var range = document.createRange();
  var copyText = document.getElementById(elementId);
  if (!copyText) {
    return;
  }
  range.selectNode(copyText);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("copy")
  selection.removeAllRanges();
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {
      $(this).html($(this).html().replace(/\$API_KEY/g,
        ""
        + "login to retrieve your api-key"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

$(document).ready(function () {
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();
  console.log('apiKey', apiKey);
  console.log('email', email);

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<|endoftext|>


<commit_before>(function(w, ng){

	//APLICACION
	//'ngRoute': proporciona la dependencia $routeProvider
	var app = ng.module('accountsApp', ['ngRoute']);

	//DEPENDENCIAS DE APLICACION
	//$routeProvider: enrutador de vistas, mapeamos la vista con siu enrutador
	app.config(['$routeProvider', function($routeProvider){
		$routeProvider
			.when('/', {
				controller: 'bankAccountsController',
				templateUrl: 'view/totalCuentas.tpl.html'
			})
			.when('/nuevo', {
				controller: 'bankAccountsController',
				templateUrl: 'view/nuevaCuenta.tpl.html'
			})
			.when('/lista', {
				controller: 'bankAccountsController',
				templateUrl: 'view/listaCuentas.tpl.html'
			})
			.otherwise({
				redirectTo: '/'
			})
	}]);

	//CONTROLADORES DE APLICACION y dependencia de controlador $location
	app.controller('bankAccountsController', accountsCtrl);
	app.controller('navigationMenuController', ['$location', menuCtrl]);

})(window, window.angular);<commit_msg>anyadir controladores a las vistas a traves de la dependencia<commit_after>(function(w, ng){

	//APLICACION
	//'ngRoute': proporciona la dependencia $routeProvider
	var app = ng.module('accountsApp', ['ngRoute']);

	//DEPENDENCIAS DE APLICACION
	//$routeProvider: enrutador de vistas, mapeamos la vista con siu enrutador
	app.config(['$routeProvider', function($routeProvider){
		$routeProvider
			.when('/', {
				controller: 'bankAccountsController',
				controllerAs: 'accountsCtrl', //alias utilizado en las vistas
				templateUrl: 'view/totalCuentas.tpl.html'
			})
			.when('/nuevo', {
				controller: 'bankAccountsController',
				controllerAs: 'accountsCtrl',
				templateUrl: 'view/nuevaCuenta.tpl.html'
			})
			.when('/lista', {
				controller: 'bankAccountsController',
				controllerAs: 'accountsCtrl',
				templateUrl: 'view/listaCuentas.tpl.html'
			})
			.otherwise({
				redirectTo: '/'
			})
	}]);

	//CONTROLADORES DE APLICACION y dependencia de controlador $location
	app.controller('bankAccountsController', accountsCtrl);
	app.controller('navigationMenuController', ['$location', menuCtrl]);

})(window, window.angular);<|endoftext|>


<commit_before>(function(){
  'use strict';

  document.addEventListener('DOMContentLoaded', function(){

  });//DOM CONTENT LOADED
})();
<commit_msg>declaramos las variables<commit_after>(function(){
  'use strict';

  document.addEventListener('DOMContentLoaded', function(){
    //campos datos usuarios
    var nombre = document.getElementById('nombre');
    var apellido = document.getElementById('apellido');
    var email = document.getElementById('email');

    //campos pases
    var pase_dia = document.getElementById('pase_dia');
    var pase_dosdias = document.getElementById('pase_dosdias');
    var pase_completo = document.getElementById('pase_completo');

    //botones y divs
    var calcular = document.getElementById('calcular');
    var errorDiv = document.getElementById('error');
    var botonRegistro = document.getElementById('btnRegistro');
    var resultado = document.getElementById('lista-productos');

  });//DOM CONTENT LOADED
})();
<|endoftext|>


<commit_before>$(document).ready(function(){
  // Change this to the correct selector.
  //$('#fixed-header').midnight();
  $("#part-0").height($(window).height() - 60);
});

//jQuery(".main-header").fitText(1.8);

var side_open = false;
var is_mobile = false;

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 	is_mobile = true;
}

if(is_mobile){

}

var editor = CodeMirror(document.getElementById("code"),{
    lineNumbers: true,
    mode: "swift",
    theme: "pastel-on-dark",
    lineWrapping: false,
    indentUnit: 4,
    indentWithTabs: true
});
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "lib/intro.swift", true);
txtFile.onreadystatechange = function()
{
	if (txtFile.readyState === 4) {  // document is ready to parse.
		if (txtFile.status === 200) {  // file is found
			var allText = txtFile.responseText;
			editor.setValue(allText);
		}
	}
}
txtFile.send(null);

function skill(){
  $('#part-2').slideToggle();
  if($("#skill").attr("shape") === "cancel"){
    $("#skill").attr("shape","plus");
  }
  else{
    $("#skill").attr("shape","cancel");
  }
}

function cyc(){
  $('#part-3').slideToggle();
  if($("#cyc").attr("shape") === "cancel"){
    $("#cyc").attr("shape","plus");
  }
  else{
    $("#cyc").attr("shape","cancel");
  }
}

function proj(){
  $('#part-4').slideToggle({
    complete: function(){
      editor.refresh();
    }
  });

  if($("#proj").attr("shape") === "cancel"){
    $("#proj").attr("shape","plus");
  }
  else{
    $("#proj").attr("shape","cancel");
  }
}

function xp(){
  $('#part-6').slideToggle();
  if($("#xp").attr("shape") === "cancel"){
    $("#xp").attr("shape","plus");
  }
  else{
    $("#xp").attr("shape","cancel");
  }
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(){
  // Change this to the correct selector.
  //$('#fixed-header').midnight();
  $("#part-0").height($(window).height() - 60);
});

jQuery(".main-header-1").fitText();

var side_open = false;
var is_mobile = false;

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 	is_mobile = true;
}

if(is_mobile){

}

var editor = CodeMirror(document.getElementById("code"),{
    lineNumbers: true,
    mode: "swift",
    theme: "pastel-on-dark",
    lineWrapping: false,
    indentUnit: 4,
    indentWithTabs: true
});
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "lib/intro.swift", true);
txtFile.onreadystatechange = function()
{
	if (txtFile.readyState === 4) {  // document is ready to parse.
		if (txtFile.status === 200) {  // file is found
			var allText = txtFile.responseText;
			editor.setValue(allText);
		}
	}
}
txtFile.send(null);

function skill(){
  $('#part-2').slideToggle();
  if($("#skill").attr("shape") === "cancel"){
    $("#skill").attr("shape","plus");
  }
  else{
    $("#skill").attr("shape","cancel");
  }
}

function cyc(){
  $('#part-3').slideToggle();
  if($("#cyc").attr("shape") === "cancel"){
    $("#cyc").attr("shape","plus");
  }
  else{
    $("#cyc").attr("shape","cancel");
  }
}

function proj(){
  $('#part-4').slideToggle({
    complete: function(){
      editor.refresh();
    }
  });

  if($("#proj").attr("shape") === "cancel"){
    $("#proj").attr("shape","plus");
  }
  else{
    $("#proj").attr("shape","cancel");
  }
}

function xp(){
  $('#part-6').slideToggle();
  if($("#xp").attr("shape") === "cancel"){
    $("#xp").attr("shape","plus");
  }
  else{
    $("#xp").attr("shape","cancel");
  }
}
<|endoftext|>