<?php
	session_start();
	include 'myUniversalVars.php';
	include 'myDBFunctions.php';
	
	// if this user isn't logged in then...
	if(!isset($_SESSION['login'])){ // redirect to login page...
		header( 'Location: login.php' ) ;
	}
	
	$db = dbConnect();
	
	$perms = getPermissions($db, $_SESSION['login']);
	if (!($perms & $pmAdmin)){
        header( 'Location: /' );
        $connection = null;
        die;
	}
    
    /* TODO: new campus/building/room should select itself in list */
?>

	<script>
		var myCampusCG = '';
		var myBuildingCG = '';
		var myRoomCG = '';
		
        $(function() {
            getCampusOptionsCG();
            
            $( "#translations" ).dialog({
                modal: true,
                autoOpen: false,
                width: 'auto'
            });
		});
        
		function setSelectDefault(selectedList) { // if there is something to select in this list, 1st item chosen
			var elt = document.getElementById(selectedList);
			var itemCount = elt.getElementsByTagName("option").length;
			//alert(itemCount);
			if ( itemCount > 1 ) { 
				setSelectedText(selectedList, 1);
			}else{
				setSelectedText(selectedList, 0);
			}
		}
		
		function setSelectedText(elementId, ndx) {
			var elt = document.getElementById(elementId);
			elt.selectedIndex = ndx;
		}
		
		function setSelectByText(elName, txt) {
			alert("Element="+elName+" Selection="+txt);
			$("#"+elName).val(txt);
		}
		
		function getSelectedText(elementId) {
			var elt = document.getElementById(elementId);

			if (elt.selectedIndex == -1)
				return null;

			//alert(elt.options[elt.selectedIndex].text);
			return elt.options[elt.selectedIndex].text;
		}
        
        function selectClickCG(selectedList) {
            var elt = document.getElementById(selectedList);
            if (elt.selectedIndex == -1)
                return null;
            var mySelection = elt.options[elt.selectedIndex].text;
            if ( selectedList == 'campusList' ) {
                myCampusCG = mySelection;
                getBuildingOptionsCG(myCampusCG);
                //getRoomOptions(myBuildingCG);
                document.getElementById('buildingList').focus();
            }
            if ( selectedList == 'buildingList' ) {
                myBuildingCG = mySelection;
                getRoomOptionsCG(myBuildingCG);
            }
            if ( selectedList == 'roomList' ) {
                myRoomCG = mySelection;
                getDevices();
            }
            return mySelection;
        }
		
		function newCampus(){
			var new_Campus = prompt("New campus name?");
			if (new_Campus) {
				$.post(
					'usmCG_newCampus.php', 
					{ campus: new_Campus },
					function(data,status) {
						getCampusOptionsCG();
                        /*$('#campusList').val(new_Campus);
                        myCampusCG = new_Campus;
                        getBuildingOptionsCG();*/
					}
				);
			}
		}
		
		function getCampusOptionsCG(){
			$.get(
				'usmCG_getCampusOptions.php', 
				function(data,status) {
					$('#campusList').html(data);
					myCampusCG = getSelectedText('campusList');
					getBuildingOptionsCG();
				}
			);
		}
		
		function delCampus(){
            var ans = confirm("Delete "+myCampusCG+"?");
            if(ans) {
                $.post(
                    'usmCG_delCampus.php',
                    {campus: myCampusCG},						
                    function(data,status) {
                        getCampusOptionsCG();
                    }
                );
            }
		}
		
		function newBuilding(){
			var new_Building = prompt("New building name?");
			if (new_Building) {
				$.post(
					'usmCG_newBuilding.php', 
					{
						campus: myCampusCG,
						building: new_Building
					},
					function(data,status) {
						getBuildingOptionsCG();
                        /*$('#buildingList').val(new_Building);
                        myBuildingCG = new_Building;
                        getRoomOptionsCG();*/
					}
				);
			}
		}
		
		function getBuildingOptionsCG(){
			$.get(
				'usmCG_getBuildingOptions.php', 
				{ campus: myCampusCG },
				function(data,status) {
					$('#buildingList').html(data);
					myBuildingCG = getSelectedText('buildingList');
					getRoomOptionsCG();
				}
			);
		}
		
		function delBuilding(){
            var ans = confirm("Delete "+myBuildingCG+"?");
            if(ans) {
                $.post(
                    'usmCG_delBuilding.php', 
                    {
                        campus: myCampusCG,
                        building: myBuildingCG
                    },
                    function(data,status) {
                        getBuildingOptionsCG();
                    }
                );
            }
		}
		
		function newRoom() {
			var new_Room = prompt("New room name?")
			if (new_Room) {
				$.post(
					'usmCG_newRoom.php', 
					{
						campus: myCampusCG,
						building: myBuildingCG,
						room: new_Room
					},
					function(data,status) {
                        getRoomOptionsCG();
                        /*$('#roomList').val(new_Room);
                        myRoomCG = new_Room;
                        getDevices();*/
					}
				);
			}
		}
		
		function getRoomOptionsCG() {
			$.get(
				'usmCG_getRoomOptions.php', 
				{ 
					campus: myCampusCG,
					building: myBuildingCG
				},
				function(data,status) {
					$('#roomList').html(data);
					myRoomCG = $('#roomList').val();
					getDevices();
				}
			);
		}
        
		function delRoom(){
			$.post(
				'usmCG_delRoom.php', 
				{
					campus: myCampusCG,
					building: myBuildingCG,
                    room: myRoomCG
				},
				function(data,status) {
					getRoomOptionsCG();
					//setSelectDefault('roomList');
				}
			);
		}
		
		function newDevice() {
			var new_Device = prompt("AMX device name?\n(dvDisplay, etc)");
            
			if (new_Device) {
				var deviceCaption = prompt("New device caption?");
                
				if (deviceCaption) {
					$.post(
						'usmCG_newDevice.php', 
						{
							campus: myCampusCG,
							building: myBuildingCG,
							room: myRoomCG,
							device: new_Device,
							caption: deviceCaption
						},
						function(data,status) {
							getDevices();
						}
					);
				}
			}
		}
		
		function getDevices() {
			$.get(
				'usmCG_getDevices.php', 
				{ 
					campus: myCampusCG,
					building: myBuildingCG,
					room: myRoomCG
				},
				function(data,status) {
					$('#dvDevices').html(data);
				}
			);
		}
		
		function delDevice(ndx) {
			$.post(
				'usmCG_delDevice.php', 
				{ id: ndx },
				function(data,status) {
					getDevices();
				}
			);
		}
		
		function newProp(ndx) {
			var newProp = prompt("New property caption?");
			if (newProp) {
				$.post(
					'usmCG_newProp.php', 
					{
						device_id: ndx,
						name: newProp
					},
					function(data,status) {
						getDevices();
					}
				);
			}
		}
		
		function delProp(id) {
			$.post(
				'usmCG_delProp.php', 
				{ id: id },
				function(data,status) {
					getDevices();
				}
			);
		}

        function updateDeviceCaption(id) {
			$.post(
				'usmCG_updateDeviceCaption.php', 
				{
					id: id,
					caption: $('#' + id).val()
				}
			);
		}
        
        function updateProperty(id, column, element_id) {
			var value = $('#'+element_id).val();
			$.post(
				'usmCG_updateProperty.php', 
				{
					id: id,
					column: column,
					value: value
				}
			);
		}
		
		function setPropAllowReset(id, element_id) {
			var value = $('#' + element_id).is(':checked') ? 1 : 0;

			$.post(
				'usmCG_updateProperty.php', 
				{
					id: id,
                    column: 'ALLOWRESET',
					value: value
				}
			);
		}
		
		function setPropCapitalize(id, element_id) {
			var value = $('#' + element_id).is(':checked') ? 1 : 0;

			$.post(
				'usmCG_updateProperty.php', 
				{
					id: id,
                    column: 'CAPITALIZE',
					value: value
				}
			);
		}
        
        function generateCode() {
            var params = $.param({
                campus: myCampusCG,
                building: myBuildingCG,
                room: myRoomCG
            });
        
            window.location.href = 'usmCG_generator.php' + '?' + params;
        }

        function newTranslation(property_id) {
            var orig = prompt("What is the original value?");
            var tran = prompt("What is the translated value?");
        
            if (orig && (tran !== null)) {
                $.post(
                    'usmCG_newTranslation.php',
                    {
                        property_id: property_id,
                        name: orig,
                        translation: tran
                    },
                    function(data) {
                        getTranslations(property_id);
                        getDevices();
                    }
                );
            }
        }

        function deleteTranslation(property_id, translation_id) {
            $.post(
                'usmCG_delTranslation.php',
                { id: translation_id },
                function(data) {
                    getTranslations(property_id);
                    getDevices();
                }
            );
        }
        
        function editTranslation(id, name_element, translation_element, property_id) {
            $.post(
                'usmCG_setTranslation.php',
                {
                    id: id,
                    name: $('#' + name_element).val(),
                    translation: $('#' + translation_element).val()
                },
                function(data) {
                    getTranslations(property_id);
                }
            );
        }
        
        function getTranslations(property_id) {
            $.get(
                'usmCG_getTranslations.php',
                {id: property_id},
                function(data) {
                    $( "#translations" ).dialog({
                        title: data['title'],
                        /*beforeClose: function(event, ui) {
                            getDevices();
                        }*/
                    });
                    
                    $( "#translations" ).html(data['table']);
                    $( "#translations" ).dialog( "open" );
                }
            );
        }
	</script>
    
    <div id="boxWrap">
        <div id="pickTable">
            <div>
                <label for="campusList">Campus:</label>
                <select id="campusList" onchange="selectClickCG('campusList')"></select>
            </div>
            
            <div>
                <label for="buildingList">Building:</label>
                <select id="buildingList" onchange="selectClickCG('buildingList')"></select>
            </div>
            
            <div>
                <label for="roomList">Room:</label>
                <select id="roomList" onchange="selectClickCG('roomList')"></select>
            </div>
            
            <span style="display: block;">
                <button id="newCampus" onclick="newCampus()">New Campus</button>
                <button id="newBuilding" onclick="newBuilding()">New Building</button>
                <button id="newRoom" onclick="newRoom()">New Room</button>
            </span>
            
            <span style="display: block;">
                <button id="delCampus" onclick="delCampus()">Del Campus</button>
                <button id="delBuilding" onclick="delBuilding()">Del Building</button>
                <button id="delRoom" onclick="delRoom()">Del Room</button>
            </span>
        </div>
    </div>    

    <div id="dvDevices"></div>
    <button id="newDev" onclick="newDevice()">New Device</button>
    <button id="generate" onclick="generateCode()">Generate</button>

    <div id="translations" title="Translations"></div>