function blinkIt() 
{
    if (!document.all) return;
    else {
	for(i=0;i<document.all.tags('blink').length;i++){
	    s=document.all.tags('blink')[i];
	    s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
	}
    }
}

setInterval('blinkIt()',1000);

// Open new Document in current browser
function goTo(site)
{
    open(site,'_parent');
}

function windowWidth () {
  if (window.innerWidth) {
    return window.innerWidth;
  } else if (document.body && document.body.offsetWidth) {
    return document.body.offsetWidth;
  } else {
    return 0;
  }
}

function windowHeight () {
  if (window.innerHeight) {
    return window.innerHeight;
  } else if (document.body && document.body.offsetHeight) {
    return document.body.offsetHeight;
  } else {
    return 0;
  }
}

function waitGoto (uri) 
{
    try {
	if(DOM || MS) {
	    e = getElem("id", "wait", null);
	    e.style.top = '200px';
	    e.style.left = (windowWidth() / 2 - 100) + 'px';
	    e.style.visibility = "visible";
	}
	location = uri;
    }
    catch (ex) {
	e.style.visibility = "hidden";
	alert ("Error: " + ex.toString());
    }
}

function waitSubmit (myform) 
{
    try {
	if(DOM || MS) {
	    e = getElem("id", "wait", null);
	    e.style.top = '200px';
	    e.style.left = (windowWidth() / 2 - 100) + 'px';
	    e.style.visibility = "visible";
	}
        myform.submit ();
    }
    catch (ex) {
	e.style.visibility = "hidden";
	alert ("Error: " + ex.toString());
    }
}

function setval(id,val)
{
    //document.getElementById(id).firstChild.data = val." ";
    if (document.getElementById(id).innerHTML) {
  	if (val == '' )
	    document.getElementById(id).innerHTML = "&nbsp;";
  	else
	    document.getElementById(id).innerHTML =  val;
    }
}

function getLeft(l)
{
    if (l.offsetParent) return (l.offsetLeft + getLeft(l.offsetParent));
    else return (l.offsetLeft);
}

function getTop(l)
{
    if (l.offsetParent) return (l.offsetTop + getTop(l.offsetParent));
    else return (l.offsetTop);
}

var origlnk = new Array();

var pve_ajax_dropdown_lock = 0;

function dropdown (id,vis,posname,link)
{
    if (vis==1) {
	pve_ajax_dropdown_lock = 1;
	if (link) {
	    for (var i=0; i<=100; i++) {
		var elem = id + "_ddlnk_" + i;
		var e = $(elem);
		if (e) {
		    if (origlnk[elem] == undefined ) {
			origlnk[elem] = e.href;
		    }
	            var ol = origlnk[elem];
		    if (ol.match(/^javascript:(.*)\(\)$/)) {
			var func = RegExp.$1;
			var par = link.toQueryParams();
			e.href = 'javascript:' + func + '(' + $H(par).toJSON() + ')';
		    } else {
			e.href = ol + link;
		    }
		} else {
		    i=1000;
		}
	    }
	}
	if (posname) {
	    var pos = document.getElementsByName(posname)[0];
	    var e = $(id);
	    e.style.position = 'absolute';
	    e.style.left = getLeft(pos) + 'px';	
	    e.style.top = getTop(pos) + 'px';
	}
	    
	$(id).style.visibility = "visible";
    } else {
	pve_ajax_dropdown_lock = 0;
	$(id).style.visibility = "hidden";
    }
}

/* form handling and verification */
    
function pve_form_save(name, action) {
    try {
	var e = $("wait");   		    
	if (document.body.offsetHeight ) {
	    e.style.top = 200;
	    e.style.left = document.body.offsetWidth / 2 - 100;     
	}
	e.style.visibility = "visible";

	$('form_' + name + '_submit').value = action;
	$(name).submit();
    }
    catch (ex) {
	e.style.visibility = "hidden";
	alert ("Error: unable to upload file (" + ex.toString() + ")");
    }
}

function pve_form_validate_natural (name, max) {
    var e = $(name);
    var input = e.value;
    if(!input.match (/^[0-9]*$/)) {
	e.value = input.replace (/[^0-9]+/g, '');
    }
    if (max && e.value > max) {
	e.value = max;
    }
    var ov = e.value;
    if (e.value == '' ) e.value = e.defaultValue;     
    if (ov == '' ) e.select();     
}

function pve_form_checknotempty (name) {
    var e = $(name); 
    var ov = e.value;
    if (e.value == '' ) e.value = e.defaultValue;     
    if (ov == '' ) e.select();     
}
    
function pve_form_ip_keyfilter (evt,name,next) {
    var e = $(name); 
 
    var keyCode = evt.which ? evt.which : evt.keyCode;

    if (e.value == 0 && keyCode == 48) return false;
 
    if (next && keyCode == 190) $(next).select();

    return (keyCode != 32 && keyCode <= '9'.charCodeAt()) ||
	(keyCode >=96 && keyCode <=105); 
}    

/* utility functions to open vnc windows */
function pve_openvz_console (cid, veid) {

    var url = "/openvz/console-direct.htm?cid=" + cid + '&veid=' + veid;
    var nw = window.open(url, '_blank', "innerWidth=745,innerheight=400");
    nw.focus();
}
 
function pve_qemu_console (cid, veid) {
    var nw = window.open("/qemu/vnc-direct.htm?cid=" + cid + '&veid=' + veid, 
			 "_blank", "innerWidth=640,innerheight=400");
    nw.focus();
}

function pve_console (args) {
    var cid = args['cid'];
    var veid = args['veid'];
    var type = args['type'];

    if (type == 'openvz') {
	pve_openvz_console (cid, veid);
    } else if  (type == 'qemu') {
	pve_qemu_console (cid, veid);
    }
}

/* realtime viewer */

function commandViewer (jsvar, viewid, upid, statusid, abortid) {

    this.cur_command_timout = null;
 
    this.jsvar = jsvar;
    this.viewid = viewid;
    this.upid = upid;
    this.statusid = statusid;
    this.abortid = abortid;

    this.scroll_move_to_end = 1;

    this.restart = function  () {

	clearTimeout (this.cur_command_timout);

	this.cur_command_timout = setTimeout (function () { 
	    this.start (); 
	}.bind(this), 1);
    }

    this.start = function () {

	clearTimeout (this.cur_command_timout);

	// HACK: 'noautoupdate' does not exist, so Ajax.Updater does not update
	// anything automatically

	this.updater = new Ajax.Updater ('noautoupdate', '/ws/command', {
	    method:'get',
	    parameters: { 
			  upid: this.upid, 
			  jsvar: this.jsvar 
	    },
	    onSuccess: function(transport) {
		var json = transport.responseText.evalJSON(true);
		var node = $(this.viewid);

		var offset = node.scrollTop - node.scrollHeight + node.clientHeight;

		if (offset == 0) {
		    this.scroll_move_to_end = 1;
		}

		node.update (json.html);

		if (this.scroll_move_to_end && (node.scrollHeight > node.clientHeight)) {
		    this.scroll_move_to_end = 0;
		    node.scrollTop = node.scrollHeight - node.clientHeight;
		}

		$(this.statusid).update (json.status);
		
		if (json.running) {
		    this.cur_command_timout = setTimeout (function () { this.start (); }.bind(this), 1000);
		    $(this.abortid).update ("Abort");
		} else {
		    $(this.abortid).update ("");
		}
	    }.bind(this),
	    onFailure: function(transport) {
		var status = "Server not reachable";

		if (transport.status == 401) {
		    status = "session expired, please login again";
		}

		$(this.viewid).update ("");

		$(this.statusid).update (status);
		
		this.cur_command_timout = setTimeout (function () { this.start (); }.bind(this), 1000);
		$(this.abortid).update ("");
	    }.bind(this)
	});
    }
}

function command_abort (upid) {

    new Ajax.Request ('/ws/command_abort?upid=' + encodeURIComponent (upid), {
	method: 'get'
    });

    return undefined;
}

function logViewer (viewid, service, serviceid, filterid, statusid, trackid) {

    this.viewid = viewid;
    this.service = service;
    this.serviceid = serviceid;
    this.filterid = filterid;
    this.statusid = statusid;
    this.trackid = trackid;
    
    this.cur_timout = null;
    this.updater = undefined;

    this.scroll_move_to_end = 1;

    if (this.filterid) {
	new Form.Element.Observer (this.filterid, 0.2, // 200 milliseconds
				   function (el, value) { 
	    this.scroll_move_to_end = 1;
	    clearTimeout (this.cur_timout);
	    this.start(); 
	}.bind(this));
    }

    if (this.serviceid) {
	new Form.Element.Observer (this.serviceid, 0.2, // 200 milliseconds 
				   function (el, value) {
	    
	    this.scroll_move_to_end = 1;
	    clearTimeout (this.cur_timout);
	    this.start(); 
	}.bind(this));
    }

    this.start = function () {

	var filter = this.filterid ? $(this.filterid).getValue() : '';
	var service = this.serviceid ? $(this.serviceid).getValue() : this.service;

	clearTimeout (this.cur_timout);

	// HACK: 'noautoupdate' does not exist, so Ajax.Updater does not update
	// anything automatically

	this.updater = new Ajax.Updater ('noautoupdate', '/ws/viewlog', {

	    method:'get',
	    parameters: { filter: filter, service: service, trackid: this.trackid},

	    onSuccess: function(transport) {
		var json = transport.responseText.evalJSON(true); 
		var node = $(this.viewid);

		var offset = node.scrollTop - node.scrollHeight + node.clientHeight;

		if (offset == 0) {
		    this.scroll_move_to_end = 1;
		}

		node.update (json.html);

		if (this.scroll_move_to_end && (node.scrollHeight > node.clientHeight)) {
		    this.scroll_move_to_end = 0;
		    node.scrollTop = node.scrollHeight - node.clientHeight;
		}

		$(this.statusid).update (json.status);
		
		if (json.running) {
		    this.cur_timout = setTimeout (function () { this.start (); }.bind(this), 1000);
		}
	    }.bind(this),
	    onFailure: function(transport) {
		var status = "Server not reachable";

		if (transport.status == 401) {
		    status = "session expired, please login again";
		}

		$(this.viewid).update ("");

		$(this.statusid).update (status);
		
		this.cur_timout = setTimeout (function () { this.start(); }.bind(this), 1000);
	    }.bind(this)
	});
    }
}

function timeViewer (viewid) {

    this.viewid = viewid;

    this.start = function () {
	var cd = new Date();
	var ta = $(this.viewid).innerHTML.split (':');
	if (!ta[0] || !ta[1] || !ta[2]) { return; } 
	var sd = new Date (cd.getFullYear(), cd.getMonth(), cd.getDay(), ta[0], ta[1], ta[2]);
	var nt = new Date (sd.getTime() + 1000);
	var h = nt.getHours();
	if (h < 10) { h = '0' + h; }
	var m = nt.getMinutes();
	if (m < 10) { m = '0' + m; }
	var s = nt.getSeconds();
	if (s < 10) { s = '0' + s; }
	$(this.viewid).innerHTML = h + ':' + m + ':' + s;
    }

    new PeriodicalExecuter (function () { this.start(); }.bind(this), 1);

    new Ajax.PeriodicalUpdater ( { success: viewid }, '/ws/servertime', { frequency: 5 });
    
}

function wsViewer (viewid, statusid, period, wsurl, wsargs) {

    this.viewid = viewid;
    this.statusid = statusid;
    this.period = period * 1000;

    this.cur_timout = null;

    this.scroll_move_to_end = 1;

    this.start = function () {

	clearTimeout (this.cur_timout);

	// HACK: 'noautoupdate' does not exist, so Ajax.Updater does not update
	// anything automatically

	this.updater = new Ajax.Updater ('noautoupdate', wsurl, {
	    method: 'get',
	    parameters: wsargs,
	    onSuccess: function(transport) {
		var json = transport.responseText.evalJSON(true);
		var node = $(this.viewid);

		var offset = node.scrollTop - node.scrollHeight + node.clientHeight;

		if (offset == 0) {
		    this.scroll_move_to_end = 1;
		}


		if (!pve_ajax_dropdown_lock) {
		    node.update (json.html);

		    if (this.scroll_move_to_end && (node.scrollHeight > node.clientHeight)) {
			this.scroll_move_to_end = 0;
			node.scrollTop = node.scrollHeight - node.clientHeight;
		    }
		}


		if (this.statusid) {
		    $(this.statusid).update (json.status);
		}

		this.cur_timout = setTimeout (function () { this.start (); }.bind(this), this.period);
	    }.bind(this),
	    onFailure: function(transport) {
		var status = "Server not reachable";

		if (transport.status == 401) {
		    status = "session expired, please login again";
		}

		if (this.statusid) {
		    $(this.viewid).update ("");

		    $(this.statusid).update (status);
		}

		this.cur_timout = setTimeout (function () { this.start (); }.bind(this), this.period);
	    }.bind(this)
	});
    }
}

function vzlistViewerOLD (viewid, statusid, cid) {

    this.viewid = viewid;

    new Ajax.PeriodicalUpdater ( { success: viewid }, '/ws/vzlist', { 
	frequency: 5, 
	parameters: { cid: cid }
    });
    
}


