<!DOCTYPE html>
<html>
<head>
    <link rel="shortcut icon" href="images/favicon.ico">
    <!--
    noVNC example: simple example using default UI
    Copyright (C) 2012 Joel Martin
    Copyright (C) 2013 Samuel Mannehed for Cendio AB
    noVNC is licensed under the MPL 2.0 (see LICENSE.txt)
    This file is licensed under the 2-Clause BSD license (see LICENSE.txt).

    Connect parameters are provided in query string:
        http://example.com/?host=HOST&port=PORT&encrypt=1&true_color=1
    -->
    <title>VM</title>

    <meta charset="utf-8">
    <meta http-equiv="cache-control" content="no-cache">
    <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
                Remove this if you use the .htaccess -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <!-- Apple iOS Safari settings -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <!-- App Start Icon  -->
    <link rel="apple-touch-startup-image" href="images/screen_320x460.png" />
    <!-- For iOS devices set the icon to use if user bookmarks app on their homescreen -->
    <link rel="apple-touch-icon" href="images/screen_57x57.png">
    <!--
    <link rel="apple-touch-icon-precomposed" href="images/screen_57x57.png" />
    -->


    <!-- Stylesheets -->
    <link type="text/css" rel="stylesheet" href="include/font-awesome/css/font-awesome.css" />    
    <link rel="stylesheet" href="include/base.css" />
    <link rel="alternate stylesheet" href="include/black.css" TITLE="Black" />
    <link rel="alternate stylesheet" href="include/blue.css" TITLE="Blue" />

    <!--
    <script type='text/javascript'
        src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
    -->

	<link href="/media/css/bootstrap.css" rel="stylesheet">
	<link href="/media/css/bootstrap-responsive.css" rel="stylesheet" />
    <link href="/media/css/jquery.alerts.css" rel="stylesheet" />
    <link href="/media/css/jquery.treeview.css" rel="stylesheet" />
    <link rel="shortcut icon" href="/media/img/favicon.ico">
    <script src="/media/js/jquery.js"></script>
    <script src="/media/js/bootstrap-alert.js"></script>
    <script src="/media/js/bootstrap-modal.js"></script>
    <script src="/media/js/bootstrap-button.js"></script>
    <script src="/media/js/bootstrap-collapse.js"></script>
    <script src="/media/js/bootstrap-carousel.js"></script>
    <script src="/media/js/bootstrap-typeahead.js"></script>
    <script src="/media/js/bootstrap-file-input.js"></script>
    <script src="/media/js/jquery.fullscreen-min.js"></script>
    <script src="/media/js/QFolderTree.js"></script>
    <script src="/media/js/jquery.treeview.js"></script>    
    <script src="/media/js/QUtility.js"></script>
    <script src="/media/js/jquery.alerts.js"></script>
    <script src="/media/js/templates/vm.js"></script>
    
    <style type='text/css'>
		body { 
		    background: #444444; 
		}
		.btn {
            margin: 10px 5px;
        }
	.btn:hover {
	  background-position: 0 -2195px;
	  outline: 0;
	  -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);
	     -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);
	          box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);
	}
	
        .ctrl-column {
            position:absolute;
            background-color: #EEEEEE;
	    box-shadow: 1px 0 5px #000000;
            vertical-align: top;
            width: 52px;
            height: 100%;
            text-align: center;
	    margin-left:-52px;
	    z-index: 1000;
	    top: 0;
	    transition: all 0.3s ease-in 0s;
	    -webkit-transition: all 0.3s ease-in 0s;
        }   
        
	.vnc-ctrl-more {
	    position: absolute;
	    vertical-align: top;
	    background-image: url("images/pop_more.png");
	    background-position: center top;
	    background-repeat: no-repeat;
	    /*border: 1px solid #999;*/
	    margin-left: 0px;
	    width: 43px;
	    height: 36px;
	    z-index: 1000;
	    top: 0;
	    transition: all 0.3s ease-in 0s;
	    -webkit-transition: all 0.3s ease-in 0s;
	    cursor:pointer;
	}        
	.vnc-ctrl-more:hover {
	    background-image: url("images/pop_more_hover.png");
	}
	.vnc-ctrl-less {
	    margin-left: 52px;
	    background-image: url("images/pop_less.png");
	}       
	.vnc-ctrl-less:hover {
	    background-image: url("images/pop_less_hover.png");
	}

	.multiKeyDark{
	    background-color: #333;
	    display: block;
	    width: 461px;    
	    height: 233px;
	    position: absolute;
	    top:30px;
	    left:50%;
	    margin-left:-230px;
	    border-radius: 5px;
	}

	.multiKeyMain{
	    height:310px;
	}

	.multiKeyBtn{
	    background: linear-gradient(to bottom, #5c5c5c 1%,#4c4c4c 25%,#4c4c4c 75%,#5c5c5c 100%);
	    border: 1px solid #000000;
	    border-radius: 5px;
	    box-shadow: 0 0 3px #646464 inset;
	    float:left;
	    display: inline-block;
	    width: 50px;    
	    height: 50px;
	    margin-left:5px;
	    margin-top:5px;
	    text-align: center;
	    cursor: pointer;
	    position:relative;
	}

	.multiKeyBtn:hover{
	    background: linear-gradient(to bottom, #6c6c6c 1%,#5c5c5c 25%,#5c5c5c 75%,#6c6c6c 100%);
	}

	.multiKeyBtnText{
	    background-color: transparent;
	    font-weight:bold;
	    color:#FFF;
	    position:relative;
	    top:15px;
	    font-size: 14px;
	    font-weight: bold;    
	}

	.multiKeyInput{
	    width:461px;
	    height:25px;
	    margin:275px 0px 0px 40px;
	    border:1px solid #7B7D7F;	
	}

	.multiKeyFocus{
	    border-radius:3px;
	    width:6px;
	    height:6px;
	    background-color:#0F0;
	    position:absolute;
	    top:0px;
	    left:0px;
	    margin-top:5px;
	    margin-left:5px;
	}

	.multiKeyFocusOff{
	    display:none;
	}

	.keyboardModalSmall{
		width:320px;
	}
	
	.keyboardModalChildrenSmall{
		height:190px;
	}
	
	.multiKeyMainSmall{
		height:50px;
	}
	
	.multiKeyDarkSmall{
		top:0px;
		margin-top:-30px;
		-webkit-transform:scale(.6,.6);
		-moz-transform:scale(.6,.6);
		transform:scale(.6,.6);
	}
	
	.multiKeyInputSmall{
		margin:160px 0px 0px 15px;
		width:270px;
	}
	
	.multiKeyBtnTextSmall{
		font-weight:normal;
		font-size:17px;
	}
	.qualityType{
		bottom: 2px;
		font-weight: bold;
		margin-left: 14px;
		position: relative;
		text-shadow: 1px 1px 1px #000000;
		color:#666;
	}
	#remeberLogoutHint{
	border: 1px solid #a099e7;
	background-color: #e9e6f9;
		border-radius: 6px;
		left: 50%;
		top: 30px;
		position: absolute;
		z-index: 50000;
		padding: 12px 20px;
		margin-left: -300px;
		text-align: center;
		width:600px;
	}
	
	#addSSLHint{
		background-color: #FFF;
		border-radius:6px;
		height:550px;
		width:600px;
		padding:20px;
		position: absolute;
		top: 50px;
		left:50%;
		margin-left:-300px;
	}
	.hintTitle{
		color: #3581C7;
		font-size: 14px;
		font-weight: bold;
		line-height:24px;
		margin-bottom: 15px;
	}
	.hintText{
		margin-left: 45px;
		text-align: left;
		line-height:24px;
	}
	.hintNum{
		color:#F00;
		font-size: 16px;
		font-weight: bold;
		margin-right: 10px;		
	}
	</style>

</head>

<body>
<!--      <div id="left_menu" class="ctrl-menu" style="margin-left: -52px;">	start of left_menu -->  
        <div id="menu_form" class="ctrl-column">
        	<a href="#keyboardModal" style="width:38px !ie;height:22px !ie; margin-left:0px !ie;" role="button" data-toggle="modal" class="btn" title="Function Keys" onclick="openMultiKey();"><i class="vnc-multikey" style="margin-top:2px !ie;"></i></a>
        	<button id="autofitBtn" class="btn" type="button" title="Autofit: Original" onclick="OnAutofit(this);"><i id="autofitBtnIcon" class="vnc-autofit vnc-restore"></i></button>
            <button id="onFullscreenBtn" class="btn" type="button" title="Fullscreen" onclick="onFullscreen(this);"><i id="onFullscreenIcon" class="vnc-fullscreen"></i></button>
        	<button class="btn" type="button" title="Quality : High (> 20Mbit/s)" onclick="OnQualityChange(1);" style="padding: 2px 10px;"><i id="onFullscreenIcon" class="vnc-quality eye_h"><span class="qualityType"></span></i></button>
        	<button class="btn" type="button" title="Quality : Medium (> 10Mbit/s)" onclick="OnQualityChange(2);" style="padding: 2px 10px;"><i id="onFullscreenIcon" class="vnc-quality eye_m"><span class="qualityType"></span></i></button>
        	<button id="qualityType3" class="btn" type="button" title="Quality : Low (2400 - 4000 Kbit/s) - 256 Colors" onclick="OnQualityChange(3);" style="padding: 2px 10px;display:none;"><i id="onFullscreenIcon" class="vnc-quality eye_l"><span class="qualityType"></span></i></button>
        	<button id="qualityType4" class="btn" type="button" title="Quality : Ultra Low (800 ~ 1600 Kbit/s) - 64 Colors" onclick="OnQualityChange(4);" style="padding: 2px 10px;display:none;"><i id="onFullscreenIcon" class="vnc-quality eye_u"><span class="qualityType" style="margin-left:-11px;"></span></i></button>
    	</div>
        <div id="menu_more" class="vnc-ctrl-more" onclick="javascript:ctrlMenu();"></div>
<!--    </div>  end of left_menu -->
   	<div id="keyboardModal" class="modal hide fade"> <!-- keyboardModal -->
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>{% trans "Function Keys" %}</h3>
      </div>
      <div class="modal-body">
	<div id="multiKeyMain"></div>
      </div>
      <div class="modal-footer" style="height:26px;">
	<button class="btn" id='functionKeySize' style="margin-top:-1px;margin-bottom:0px;display:none" onclick="functionKeySize();">2X</button>
	<button class="btn" id='closeMultiKeyboard' data-dismiss="modal" style="margin-top:-1px;margin-bottom:0px">{% trans "Close" %}</button>
            <button class="btn" style="margin-top:-1px;margin-bottom:0px" onclick="clear_keyboard();">{% trans "Clear" %}</button>
            <button class="btn" id="sendMultiKeyboard" style="margin-top:-1px;margin-bottom:0px" disabled="true">{% trans "Send" %}</button> 	  
      </div>
    </div> <!-- /keyboardModal -->
<!--	
    <div id="qualityModal" class="modal hide fade">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>{% trans "HTML5 Session" %}</h3>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" action="" method="post" style="margin-bottom:13px;">{% csrf_token %}
          <fieldset>
              <label class="control-label">{% trans "Connection Quality" %}:</label>
              <div class="controls" style="padding-top:0;">
                <label class="radio" style="text-align:left;"><input type="radio" name="html5_quality" value="high"/>High (> 20Mbit/s)</label>
                <label class="radio" style="text-align:left;"><input type="radio" name="html5_quality" value="medium"/>Medium (> 10Mbit/s) - Max Colors</label>
                <label class="radio" style="text-align:left;"><input type="radio" name="html5_quality" value="low"/>Low (2400 - 4000 Kbit/s) - 256 Colors</label>
              </div>
          </fieldset>
      </div>
      <div class="modal-footer" style="height:26px;">
            <button class="btn" data-dismiss="modal" style="margin-top:-1px;margin-bottom:0px">{% trans "Close" %}</button>
            <button class="btn" type="button" onclick="OnQualityChange(this.form.html5_quality);" style="margin-top:-1px;margin-bottom:0px">{% trans "Apply" %}</button>   	  
        </form>
      </div>
    </div> <!-- /qualityModal -->
    <div id="right_container"> <!-- start of right_container -->
        <div id="noVNC-control-bar">
            <div id="noVNC-menu-bar" style="display:none;">
            </div>
            <!--noVNC Mobile Device only Buttons-->
            <div class="noVNC-buttons-left">
            </div>
    
            <div id="noVNC_status">{% trans "Loading" %}</div>
    
            <!--noVNC Buttons-->
            <div class="noVNC-buttons-right">
                <input type="image" src="images/drag.png"
                    id="noVNC_view_drag_button" class="noVNC_status_button"
                    title="Move/Drag Viewport">
                <div id="noVNC_mobile_buttons">
                    <input type="image" src="images/mouse_none.png"
                        id="noVNC_mouse_button0" class="noVNC_status_button">
                    <input type="image" src="images/mouse_left.png"
                        id="noVNC_mouse_button1" class="noVNC_status_button">
                    <input type="image" src="images/mouse_middle.png"
                        id="noVNC_mouse_button2" class="noVNC_status_button">
                    <input type="image" src="images/mouse_right.png"
                        id="noVNC_mouse_button4" class="noVNC_status_button">
                    <input type="image" src="images/keyboard.png"
                        id="showKeyboard" class="noVNC_status_button"
                        value="Keyboard" title="Show Keyboard"/>
                    <input type="text" autocapitalize="off" autocorrect="off"
                        id="keyboardinput" class="" value="&nbsp;"/>
                </div>
                <input type="image" src="images/ctrlaltdel.png" style="display:none;"
                     id="sendCtrlAltDelButton_original" class="noVNC_status_button"
                    title="Send Ctrl-Alt-Del" />
                <input type="image" src="images/clipboard.png" style="display:none;"
                    id="clipboardButton" class="noVNC_status_button"
                    title="Clipboard" />
                <input type="image" src="images/settings.png" style="display:none;"
                    id="settingsButton" class="noVNC_status_button"
                    title="Settings" />
                <input type="image" src="images/connect.png" style="display:none;"
                    id="connectButton" class="noVNC_status_button"
                    title="Connect" />
                <input type="image" src="images/disconnect.png" style="display:none;"
                    id="disconnectButton" class="noVNC_status_button"
                    title="Disconnect" />
            </div>
    
            <!-- Description Panel -->
            <!-- Shown by default when hosted at for kanaka.github.com -->
            <div id="noVNC_description" style="display:none;" class="">
                noVNC is a browser based VNC client implemented using HTML5 Canvas
                and WebSockets. You will either need a VNC server with WebSockets
                support (such as <a href="http://libvncserver.sourceforge.net/">libvncserver</a>)
                or you will need to use
                <a href="https://github.com/kanaka/websockify">websockify</a>
                to bridge between your browser and VNC server. See the noVNC
                <a href="https://github.com/kanaka/noVNC">README</a>
                and <a href="http://kanaka.github.com/noVNC">website</a>
                for more information.
                <br />
                <input id="descriptionButton" type="button" value="Close">
            </div>
    
            <!-- Popup Status Panel -->
            <div id="noVNC_popup_status_panel" class="">
            </div>
    
            <!-- Clipboard Panel -->
            <div id="noVNC_clipboard" class="triangle-right top">
                <textarea id="noVNC_clipboard_text" rows=5>
                </textarea>
                <br />
                <input id="noVNC_clipboard_clear_button" type="button"
                    value="Clear">
            </div>
    
            <!-- Settings Panel -->
            <div id="noVNC_settings" class="triangle-right top">
                <span id="noVNC_settings_menu">
                    <ul>
                        <li><input id="noVNC_encrypt" type="checkbox"> {% trans "Encrypt" %}</li>
                        <li><input id="noVNC_true_color" type="checkbox" checked> {% trans "True Color" %}</li>
                        <li><input id="noVNC_cursor" type="checkbox"> {% trans "Local Cursor" %}</li>
                        <li><input id="noVNC_clip" type="checkbox"> {% trans "Clip to Window" %}</li>
                        <li><input id="noVNC_shared" type="checkbox"> {% trans "Shared Mode" %}</li>
                        <li><input id="noVNC_view_only" type="checkbox"> {% trans "View Only" %}</li>
                        <li><input id="noVNC_connectTimeout" type="input"> {% trans "Connect Timeout (s)" %}</li>
                        <li><input id="noVNC_path" type="input" value="websockify"> {% trans "Path" %}</li>
                        <li><input id="noVNC_repeaterID" type="input" value=""> {% trans "Repeater ID" %}</li>
                        <hr>
                        <!-- Stylesheet selection dropdown -->
                        <li><label><strong>{% trans "Style" %}: </strong>
                            <select id="noVNC_stylesheet" name="vncStyle">
                                <option value="default">{% trans "default" %}</option>
                            </select></label>
                        </li>
    
                        <!-- Logging selection dropdown -->
                        <li><label><strong>{% trans "Logging" %}: </strong>
                            <select id="noVNC_logging" name="vncLogging">
                            </select></label>
                        </li>
                        <hr>
                        <li><input type="button" id="noVNC_apply" value="Apply"></li>
                    </ul>
                </span>
            </div>
    
            <!-- Connection Panel -->
            <div id="noVNC_controls" class="triangle-right top">
                <ul>
                    <li><label><strong>{% trans "Host" %}: </strong><input id="noVNC_host" /></label></li>
                    <li><label><strong>{% trans "Port" %}: </strong><input id="noVNC_port" /></label></li>
                    <li><label><strong>{% trans "Password" %}: </strong><input id="noVNC_password" type="password" /></label></li>
                    <li><input id="noVNC_connect_button" type="button" value="Connect"></li>
                </ul>
            </div>
    
        </div> <!-- End of noVNC-control-bar -->
        
        <div id="noVNC_screen">
            <!--<div id="noVNC_screen_pad"></div>-->
    
            <h1 id="noVNC_logo"></h1>
    
            <!-- HTML5 Canvas -->
            <div id="noVNC_container" style="text-align:center;">
                <canvas id="noVNC_canvas" width="640px" height="20px">
                            {% trans "Canvas not supported." %}
                </canvas>
            </div>
    
        </div>
        </div>  <!-- End of right_container -->
    
    <script src="include/util.js"></script>
    <script src="include/multiKeyCode.js"></script>
	<div id="document-mask" style="display:none;left:0;top:0;position:absolute;">
		<i id="loading-icon" class="icon-loading" style="position:absolute"></i>
	</div><!-- /document-mask -->
	<div id="loading-cancel" style="display:none">
		<input class="btn" name="importvm_cancel" value="Cancel">
	</div><!-- /loading-cancel -->
</body>
<script>
//var VMStateTimer = setTimeout(function(){UpdateVMState('{{ host_id }}', '{{ vname }}', {{ state }});}, 5000);
var multiKeyCode = getMultiKeyCode();
var inputKeyCode = [];
var CursorPos = {'x':0, 'y':0};
var AutoFitScale = 1;
var bAutoFit = true;
var bAutoLogin = false;
var orgCDPath = '';
var gReadOnly = false;
//{% if not super_user and not vm_permission.control %}
//gReadOnly = true;
//{% else %}
//gReadOnly = false;  
//{% endif %}

window.onbeforeunload = function(e){
    clearTimeout(VMStateTimer);
};

window.onload = function(){
	var detectBrowser = navigator.userAgent;
	var detectDevice = detectBrowser.match(/(iPad|iPhone|iPhone)/);
	var browserVersion = detectBrowser.match(/(Chrome|Firefox|MSIE)/);
	var isIE = detectBrowser.match(/(msie)\/?\s*(\.?\d+(\.\d+)*)/i);
	if(isIE!=null){
		if((isIE[2].split('.')[0])<10)
			browserVersion = null
	}
	
	if((!browserVersion)&&(!detectDevice))
		alert("This browser version is incompatible. Please use Chrome, Firefox or Internet Explorer 10.");
	
	var tightPNGBrowser = detectBrowser.match(/(Chrome|Firefox)/);
	if (tightPNGBrowser){
		$('#qualityType3').show();
		$('#qualityType4').show();
	}		
	
    //{% if state != 1 and state != 3 %}
    //	window.close();
	//{% else %}
		//{% if reload_parent %}
		//if (window.opener.window.location.href.indexOf('/{{ vname }}/') != -1) {
		//    window.opener.window.location.href = window.opener. window.location.href
		//}
		//{% endif %}
		
		//{% if force_hide_clear_btn %}
		//var url = location.origin+'/html5/{{ host_id }}/{{ vname }}/?host='+location.hostname+'&port='+WebUtil.getQueryVar('port', '')+
	    //    '&autoconnect=true&vname={{ vname }}&default=0&autofit='+WebUtil.getQueryVar('autofit', '1')+'&quality=high'+'&v={{BuildVer}}';
		//window.location.href = url;
		//return;
		//{% elif super_user or vm_permission.control %}
		//document.getElementById('ClearConfigBtn').style.display = (document.location.search.indexOf('default=1')>=0) ? '' :  'none'; 
		//{% endif %}
		////SetRadioBtnValue(document.getElementsByName('html5_quality'), WebUtil.getQueryVar('quality', 'high'));
		//
		//{% if message %}
		//alert('{{ message }}');
		//{% endif %}
		
		var snapWizard = document.getElementById('snapshotModal');
		//var qualityWizard = document.getElementById('qualityModal');
		if ('WebKitMutationObserver' in window) { // chrome
		    var observer = new WebKitMutationObserver(function (mutations) {
                mutations.forEach( function (elem) {
                    if (elem.target.style.display == 'none') { //hide
            	        UI.displayFocus();
            	    } else { //show
            	        UI.displayBlur();
            	    }
                });
            });
            observer.observe(snapWizard, {attributes: true, subtree: false});
            //observer.observe(qualityWizard, {attributes: true, subtree: false});
		} else { // firefox, opera
		    var func = function (e) {
        	    if (e.newValue.indexOf('display') == -1) {
        	        return;
        	    }
        	    if (this.style.display == 'none') { //hide
        	        UI.displayFocus();
        	    } else { //show
        	        UI.displayBlur();
        	    }
            };
		    snapWizard.addEventListener('DOMAttrModified', func);
		    //qualityWizard.addEventListener('DOMAttrModified', func);
		}
		
        bAutoFit = WebUtil.getQueryVar('autofit', '1') == '1' ? true : false;
        if (!bAutoFit) {
            document.getElementById('autofitBtn').title = "Autofit";
            $('#autofitBtnIcon').removeClass('vnc-restore');
        } 
		if (UI.isTouchDevice) {
		    var elem = document.getElementById('noVNC_canvas');
    		elem.addEventListener("mousedown", onMouseMove, false);
            elem.addEventListener("mousemove", onMouseMove, false);
            elem.addEventListener("touchstart", onMouseMove, false);
            elem.addEventListener("touchmove", onMouseMove, true);
            elem.addEventListener("touchend", onMouseMove, false);
        } else {
            $("#noVNC_canvas").mousemove(onMouseMove);
        }
	//{% endif %}
	
        //{% if snapshot_num >= 4 %}
		$('#snapshotOver').show();
		document.getElementById('btn-do-snapshot').disabled = true;
		document.getElementById('snapshot_name_value').disabled = true;
		document.getElementById('snapshot_desc_value').disabled = true;
        //{% endif %} 	
	
	
    var url = "/vmonload/{{ host_id }}/{{ vname }}/";
    makeRequest(url, '', _callbk_initial_layout);	

	var qualityBtn = $('.qualityType');
	var nowQuality = WebUtil.getQueryVar('quality', '')-1;
	qualityBtn.eq(nowQuality).parent().parent().css({'background-color':'#A8A8A8','background-image':'none'});
	
    ctrlMenu();
    setTimeout(function(){ctrlMenu()},2000);

	//var userName = "{{userName}}";
	//if((userName=='admin')&&(window.parent == window.self)){
	//	var getURL =window.location.toString();
	//	if (getURL.indexOf('firstlogin')>0){
	//		var remeberLogoutHint = '<div id="remeberLogoutHint">{% trans "Please remember to logout when you are finished." %}</div>';
	//		$(remeberLogoutHint).appendTo($('body'));
	//		setTimeout(function(){$('#remeberLogoutHint').hide();}, 3000);		
	//	}
	//}
   
}

window.onresize = function() {
    $('body').css('overflow','');
    var origW = UI.rfb.get_display().get_width();
    var origH = UI.rfb.get_display().get_height();
    var menuRight = 52;

    if (UI.isTouchDevice){
        var scaleW = (window.innerWidth)/origW;
        var scaleH = (window.innerHeight - document.getElementById('noVNC-control-bar').clientHeight)/origH;
        bAutoFit = WebUtil.getQueryVar('autofit', '1') == '1' ? true : false;
        if (bAutoFit) {
		AutoFitScale = scaleW < scaleH ? scaleW : scaleH;
        } else {
		AutoFitScale = 1;
        }
	
	if(bAutoFit){
		var newWidth = Math.floor(origW*AutoFitScale);
		document.getElementById('noVNC_canvas').style.height = Math.floor(origH*AutoFitScale) + 'px';
		document.getElementById('noVNC_canvas').style.width = newWidth + 'px';	    
		$('#noVNC_canvas').css({'position':'absolute','left':'50%','margin-left':-1*(newWidth/2)+'px'});	
	}
	else{
		if(window.innerWidth < origW){
			$('#noVNC_canvas').css({'position':'static','left':0,'margin-left':0,'width':'','height':''});
		}
		else{
			$('#noVNC_canvas').css({'position':'absolute','left':'50%','margin-left':-1*(origW/2)+'px'});
		}	
	}
    }
    else{
	    var scaleW = (window.innerWidth - menuRight*2)/origW;
	    var scaleH = (window.innerHeight - document.getElementById('noVNC-control-bar').clientHeight)/origH;
	    bAutoFit = WebUtil.getQueryVar('autofit', '1') == '1' ? true : false;
	    if (bAutoFit) {
		AutoFitScale = scaleW < scaleH ? scaleW : scaleH;
	    } else {
		AutoFitScale = 1;/*
		if (UI.isTouchDevice) {
		    return;
		}*/
	    }    
	    var noVNC_containerWidth = (window.innerWidth - menuRight);
	    var noVNC_containerHeight = (window.innerHeight - document.getElementById('noVNC-control-bar').clientHeight);
	    var newWidth = Math.floor(origW*AutoFitScale);
	    document.getElementById('noVNC_canvas').style.height = Math.floor(origH*AutoFitScale) + 'px';
	    document.getElementById('noVNC_canvas').style.width = newWidth + 'px';    
	    document.getElementById('noVNC_container').style.width = noVNC_containerWidth + 'px';
	    document.getElementById('noVNC_container').style.height = noVNC_containerHeight + 'px';    
	    if (window.innerWidth < newWidth+menuRight*2) {
		$('#noVNC_container').css({'position':'absolute','left':menuRight});
		$('#noVNC_canvas').css({'position':'absolute','left':0,'margin-left':0});
	    } else {
		$('#noVNC_container').css({'position':'absolute','left':menuRight});
		$('#noVNC_canvas').css({'position':'absolute','left':'50%','margin-left':-1*((newWidth+menuRight)/2)+'px'});
	    }    
    }
	

}

function _callbk_initial_layout(http_request)
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var json = JSON.parse(http_request.responseText);
			if (!json.success) {
			    alert("Initial request failed"+json.errors);
    			return;
			}
			InitInfo = json;
			// shareList part
			shareList = [];
			orgCDPath = InitInfo.cdr_path;
			for (var i=0; i<json.share_list.length;i++) {
				shareList.push(json.share_list[i]);
				if (json.share_list[i].name == 'Public') {
				    PublicPath = json.share_list[i].fullpath;
				}
			}
		}	
	}
}

function OnAutofit(btn)
{
    bAutoFit = !bAutoFit;
    var url = location.origin+'/html5/{{ host_id }}/{{ vname }}/?host='+location.hostname+'&port='+WebUtil.getQueryVar('port', '')+
	        '&autoconnect=true&vname={{ vname }}&default='+WebUtil.getQueryVar('default', '')+'&autofit='+(bAutoFit?'1':'0')+'&quality='+WebUtil.getQueryVar('quality', '')+'&v={{BuildVer}}';

	window.location.href = url;
}

function OnQualityChange(quality)
{
    var Qulity = quality;
    var url = location.origin+'/html5/{{ host_id }}/{{ vname }}/?host='+location.hostname+'&port='+WebUtil.getQueryVar('port', '')+
	        '&autoconnect=true&vname={{ vname }}&default='+WebUtil.getQueryVar('default', '')+'&autofit='+(bAutoFit?'1':'0')+'&quality='+Qulity+'&v={{BuildVer}}';
	window.location.href = url;
}

function OnAutoLogin(btn)
{
    bAutoLogin = !bAutoLogin;
    if (bAutoLogin) {
        $('#autoLoginIcon').addClass('vnc-autologin');
         btn.title = "Auto logout ON";
    } else {
        $('#autoLoginIcon').removeClass('vnc-autologin');
         btn.title = "Auto logout OFF";
    }
}

function onMouseMove(e)
{
    if (!bAutoFit) {
        return;
    }
    
    if (!e) {
        e = event;
    }
    
    var rect = document.getElementById('noVNC_canvas').getBoundingClientRect();
    CursorPos.x = e.pageX-rect.left;
    CursorPos.y = e.pageY-rect.top;
}


function ResetSanpshotCmps()
{
    document.getElementById('snapshot_name_value').value = '';
	document.getElementById('snapshot_desc_value').value = '';
	document.getElementById('btn-do-snapshot').style.display = "";
	document.getElementById('btn-reset-snapshot').style.display = "none";
	document.getElementById('process_info').style.display = "none";
	document.getElementById('snapshot_done_info').style.display = "none";

	url = '/vmbkgpg/{{ host_id }}/{{ vname }}/?action=getsnapshotnum';
	makeRequest(url, '', _callbk_getsnapshotnum);	
}

function _callbk_getsnapshotnum(http_request, params){
    if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var json = JSON.parse(http_request.responseText);
			if (json.snapshot_num >= 4) {
				$('#snapshotOver').show();
				document.getElementById('btn-do-snapshot').disabled = true;
				document.getElementById('snapshot_name_value').disabled = true;
				document.getElementById('snapshot_desc_value').disabled = true;
			}
			else{
				$('#snapshotOver').hide();
				document.getElementById('btn-do-snapshot').disabled = false;
				document.getElementById('snapshot_name_value').disabled = false;
				document.getElementById('snapshot_desc_value').disabled = false;
			}			
		}
	}
}

function setPassword() {
    UI.rfb.sendPassword($D('password_input').value);
    UI.toggleConnectPanel();
    return false;
}

function ctrlMenu() {
    if (document.getElementById('menu_more').className.indexOf("vnc-ctrl-less") > 0)
    {
    	document.getElementById('menu_more').className = "vnc-ctrl-more";
    	$('#menu_form').css({'margin-left':'-52px'});
    }
    else
    {
    	document.getElementById('menu_more').className = "vnc-ctrl-more vnc-ctrl-less";
    	$('#menu_form').css({'margin-left':'0px'});
    }
    //$(window).resize();
}

function openMultiKey(){
	function makeBtn(key,data){
		var btn = $('<div/>').addClass('multiKeyBtn').attr('id','multiKey_'+key).appendTo($('#multiKeyDark'));
		$('<span/>').addClass('multiKeyFocus multiKeyFocusOff').appendTo(btn);
		
		switch(parseInt(key))
		{
			case 3:			//left
				$('<span/>').addClass('multiKeyBtnText icon-long-arrow-left').css({'font-size':'28px','margin-left':-15,'margin-top':2}).appendTo(btn);
				break;
			case 4:			//up
				$('<span/>').addClass('multiKeyBtnText icon-long-arrow-up').css({'font-size':'24px','margin-top':2}).appendTo(btn);
				break;
			case 5:			//right
				$('<span/>').addClass('multiKeyBtnText icon-long-arrow-right').css({'font-size':'28px','margin-left':-12,'margin-top':2}).appendTo(btn);				
				break;
			case 12:		//down
				$('<span/>').addClass('multiKeyBtnText icon-long-arrow-down').css({'font-size':'24px','margin-top':2}).appendTo(btn);
				break;
			default:
				$('<span/>').text(data.id).addClass('multiKeyBtnText').appendTo(btn);
				break;				
		}
		
		$('#multiKey_'+key).click(function(){
			if ($('#multiKey_'+key).children().eq(0).hasClass('multiKeyFocusOff')){
				$('#multiKey_'+key).children().eq(0).removeClass('multiKeyFocusOff');
				sendMultiKey(key,'add');			
			}
			else{
				$('#multiKey_'+key).children().eq(0).addClass('multiKeyFocusOff');
				sendMultiKey(key,'remove');
			}
		});
	}
	
	function sendMultiKey(key,action){ 
		var keyString='';
		if (action=='add'){
			inputKeyCode.push(key);
		}
		else{
			inputKeyCode.splice(inputKeyCode.indexOf(key), 1);
		}

		$.each(inputKeyCode, function(sn,data){
			if(sn==0)
				keyString = multiKeyCode[data].name;
			else
				keyString = keyString + ' + ' + multiKeyCode[data].name;
		});			
		$('#multiKeyInput').val(keyString);

		if(inputKeyCode.length > 0)
			document.getElementById('sendMultiKeyboard').disabled = false;
		else
			document.getElementById('sendMultiKeyboard').disabled = true;
	}
	
	if($('#multiKeyDark').attr('id')==undefined)
	{
		$('#multiKeyMain').addClass('multiKeyMain');
		$('<div/>').attr('id','multiKeyDark').addClass('multiKeyDark').appendTo($('#multiKeyMain'));
		$('<input/>').attr({'id':'multiKeyInput','readonly':'true'}).addClass('multiKeyInput').appendTo($('#multiKeyMain'));

		$.each(multiKeyCode, function (key, data) {
			makeBtn(key,data);
		});
	}
	
	var device = navigator.userAgent;
	var isMobile = device.match(/(iPhone|iPod|iPad|Android)/);
	if(!isMobile){
		$('#keyboardModal').addClass('keyboardModalSmall');
		$('#keyboardModal').children().eq(1).addClass('keyboardModalChildrenSmall');
		$('#multiKeyMain').addClass('multiKeyMainSmall');
		$('#multiKeyDark').addClass('multiKeyDarkSmall');
		$('#multiKeyInput').addClass('multiKeyInputSmall');
		$('.multiKeyBtnText').addClass('multiKeyBtnTextSmall');
		$('#functionKeySize').css({'display':''}).text('2X');
	}
	
}

function clear_keyboard(){
	$('#multiKeyInput').val('');
	inputKeyCode=[];
	$('.multiKeyFocus').addClass('multiKeyFocusOff');
	document.getElementById('sendMultiKeyboard').disabled = true;
}

function smit_keyboard(){
	document.getElementById('snapshot_desc').value
}

function functionKeySize(){
	if($('#functionKeySize').text()=='2X'){
		$('#keyboardModal').removeClass('keyboardModalSmall');
		$('#keyboardModal').children().eq(1).removeClass('keyboardModalChildrenSmall');
		$('#multiKeyMain').removeClass('multiKeyMainSmall');
		$('#multiKeyDark').removeClass('multiKeyDarkSmall');
		$('#multiKeyInput').removeClass('multiKeyInputSmall');
		$('.multiKeyBtnText').removeClass('multiKeyBtnTextSmall');
		$('#functionKeySize').text('1X');		
	}
	else{
		$('#keyboardModal').addClass('keyboardModalSmall');
		$('#keyboardModal').children().eq(1).addClass('keyboardModalChildrenSmall');
		$('#multiKeyMain').addClass('multiKeyMainSmall');
		$('#multiKeyDark').addClass('multiKeyDarkSmall');
		$('#multiKeyInput').addClass('multiKeyInputSmall');
		$('.multiKeyBtnText').addClass('multiKeyBtnTextSmall');
		$('#functionKeySize').text('2X');
	}
}

function onFullscreen() {
	if($('#onFullscreenIcon').hasClass('vnc-fullscreenExit')){
		$(document).fullScreen(false);
		$('#onFullscreenIcon').removeClass('vnc-fullscreenExit');
	}
	else{
		$(document).fullScreen(true);
		$('#onFullscreenIcon').addClass('vnc-fullscreenExit');
	}
}

// ======= File tree part ===========
var FileFolderTree = null;
var CurrentFieldID = '';
var CurrentTreeMode = '';
var OrigCloneLoc = '';
var InitInfo = null;

function ShowFileTree(modalID, bShow)
{
    document.getElementById(modalID+'_treebody').innerHTML = '';
    if (document.getElementById(modalID+'_form')) {
        document.getElementById(modalID+'_form').style.display = bShow ? 'none' : '';
        document.getElementById(modalID+'_tree').style.display = bShow ? '' : 'none';   
    }
    if (FileFolderTree) {
        FileFolderTree.destroy();
        delete FileFolderTree;
        FileFolderTree = null;
    }
}

function OpenFileTree(initList, data)
{
    $('#closeMask').remove();
    $('#CDMenu').remove();
    var modalID=data[0], mode=data[1], elmID=data[2];
    CurrentTreeMode = mode;
    CurrentFieldID = elmID;
    ShowFileTree(modalID, true);

    var elem = document.getElementById(modalID+'_treetitle');
    if (mode == 'iso') {
        if (elem) elem.innerHTML = "{% trans 'Select one CD image' %} (*.iso)";
        FileFolderTree = new QFolderTree(MODE_SINGLE_FILE, FILTER_ISO);
    } else  if (mode == 'img') {
        if (elem) elem.innerHTML = "{% trans 'Select one HDD image' %} (*.img)";
        FileFolderTree = new QFolderTree(MODE_SINGLE_FILE, FILTER_IMG);
    } else {
        if (elem) elem.innerHTML = "{% trans 'Select one folder location' %}";
        FileFolderTree = new QFolderTree(MODE_SINGLE_FOLDER, FILTER_FOLDER);
    }

    shareList = [];
    if (initList) {
        shareList = initList;
    } else {
        for (var i=0; i<InitInfo.share_list.length;i++) {
            shareList.push(InitInfo.share_list[i]);
        }
    }
    FileFolderTree.initTree(modalID+'_treebody', shareList, InitInfo.host_name);
    
    if (mode == 'iso') {
        if (InitInfo.isos_path) {
            FileFolderTree.selectFolder(InitInfo.isos_path);
        } else {
            document.getElementById(DEFAULT_POOL_FOLDER_ID).click();
        }
    } else {
        if (InitInfo.hdds_path) {
            FileFolderTree.selectFolder(InitInfo.hdds_path);
        } else {
            document.getElementById(DEFAULT_POOL_FOLDER_ID).click();
        }
    }
}

function UpdateFocusFile(elmID)
{
    var item = FileFolderTree.getItemInfo(elmID);
	if (!item) {
	    return;
	}

	if (CurrentFieldID == "clone_loc") {
	    OrigCloneLoc = item.fullpath;
	    Update_Clone_Path();
	} else {
	    document.getElementById(CurrentFieldID).value = item.fullpath;
	    document.getElementById(CurrentFieldID).title = item.fullpath;
    	document.getElementById(CurrentFieldID+'_show').value = item.name;
    	document.getElementById(CurrentFieldID+'_show').title = item.name;
    }
	if (FileFolderTree.FocusID != "") {
		document.getElementById(FileFolderTree.FocusID).style.cssText = "";
	}
	document.getElementById(elmID).style.cssText = "background-color:lightgrey;color:midnightblue;";
	FileFolderTree.FocusID = elmID;
}

function UpdateFocusFolder(elmID)
{
    if (FileFolderTree.Mode == MODE_SINGLE_FILE) {
        return;
    }
    
    UpdateFocusFile(elmID);
    return;
}


function CDmenu(haveCD){
	if($('#CDMenu').attr('id')!=undefined){
		$('#CDMenu').remove();		
	}
	else{
		$('<div id="closeMask">').appendTo($('body'));
		var rect = $('#virtio_iso')[0].getBoundingClientRect();
		var baseLeft=rect.left+50;
		var baseTop=rect.top;	

		var CDMenu = $('<div id="CDMenu"/>').appendTo($('body'));
		var CDMenuContent = $('<div/>').addClass('menuContent').css({'left':baseLeft,'top':baseTop}).appendTo(CDMenu);

		if (haveCD=='/KVM/modules/virtio-win.iso'){
			orgCDPath = haveCD;
			CDMenuContent.append("<ul><li><div onclick='selectCD(\'eject\')'>{% trans 'Eject' %}</div></li>"+
					"<li><div onclick='selectCDtree()'>{% trans 'Insert another CD' %}</div></li></ul>");
		}		
		else if (haveCD!='none'){
			orgCDPath = haveCD;
			CDMenuContent.append("<ul><li><div onclick='selectCD(\'eject\')'>{% trans 'Eject' %}</div></li>"+
					"<li><div onclick='selectCDtree()'>{% trans 'Insert another CD' %}</div></li>"+
					"<li><div onclick='selectCD(\'insert\')'>{% trans 'Insert Driver CD' %}</div></li></ul>");			
		}
		else{
			orgCDPath = '';
			CDMenuContent.append("<ul><li><div onclick='selectCDtree()'>{% trans 'Insert another CD' %}</div></li>"+
					"<li><div onclick='selectCD(\'insert\')'>{% trans 'Insert Driver CD' %}</div></li></ul>");						
		}
		$('#closeMask').on('touchstart click',closeMenu);
		
	}	
}

function closeMenu(e){
	e.preventDefault();
	$('#CDMenu').remove();
	$('#closeMask').remove();
}

function selectCD(action,selectPath){
	$('#CDMenu').remove();
	$('#closeMask').remove();
	
	var csrfValue='csrfmiddlewaretoken='+$('#menu_form form div input').attr('value');
	var orgPath = '&cdr_path='+orgCDPath;
	var sendPath='&selectPath=';
	if(selectPath)
		sendPath='&selectPath='+selectPath;
		
	url = '/html5/1/{{ vname }}/'+action+'/';	
	makeRequest(url, csrfValue+orgPath+sendPath, _callbk_selectCD);	
	ShowMask('','',true);
}

function _callbk_selectCD(http_request){
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var json = JSON.parse(http_request.responseText);
			
			if(json.success){
				if(json.cdroms[0].cdr_path){
					$('#virtio_iso').attr({'title':"{% trans 'Eject or change CD' %}",'onclick':'CDmenu(\''+json.cdroms[0].cdr_path+'\')'});
				}
				else{
					$('#virtio_iso').attr({'title':"{% trans 'Insert CD' %}",'onclick':'CDmenu(\'none\')'});
				}
			}
			else{
				var errorStr='';
				$.each(json.errors, function(sn){
					errorStr = errorStr + json.errors[sn] +'\n';					
				});			
			
				alert(errorStr);
			}
			
		}
		CloseMask();
	}
}

function selectCDtree(){
	$('#CDMenu').remove();
	$('#closeMask').remove();
	$('#selectCDtree').click();
}

</script>
<script src="include/ui.js"></script>
</html>
