var gappl_enabled=true;      // onko gappl-sovellus enabloitu
var graph_enabled = true;    // onko grafiikkapainike enabloitu
var gappl="/graph";          // grafiikkasovelluksen virtuaalihakemiston polku
var gdoc="/GraphPage.aspx";  //Oletusdokumentti
var Graphserver = "Graphserver.aspx";
var isSvgCtlAllowed = false; // Prevents use of Adobe SVG plugin in IE 

/* 
 *Moved here from main.js
 *Object containing special character codes
 *Used by encodeSpecial();
 */
var special_chars = {
    E4: "*228;",
    F6: "*246;",
    E5: "*229;" , //å
    C4: "*196;",
    D6: "*214;",
    C5: "*197;",   //Å
    20: "*;"
};
/* encodeSpecial
 * Encodes special characters used in directory and file names
 * into character codes, used by m_ini);
 * used by statpage.js.addFavorite()
 * to encode mComm
 */ 
function encodeSpecial(s) {
    s = escape(s);
    for(var i in special_chars) {
         for (; s.indexOf("%" + i)>-1;) {
            s = s.replace("%" + i, special_chars[i]);
         }
    }
    return unescape(s);
}
/* decodeSpecial(s)
 * used by m_DoBmark() when parsing query
 */
function decodeSpecial(s) {
    for(var i in special_chars) {
         for (; s.indexOf(special_chars[i])>-1;) {
            s = s.replace(special_chars[i],"%" + i);
         }
    }
    return unescape(s);
}


function listSpecial() {
    var r = "";
    for (var i in special_chars) {
        r += "%" + i + "=" + special_chars[i] + "\n";
    }
    return r;
}
var vertiTop = findVertiTop();

function show(item){
// util
    if (true) {
        var a = "";
        var m = arguments.length;
        for(var i = 0; i < m; i++) a += arguments[i] + "\n"; 
        alert(a);
    }
}

/*
 * closes separate window
 * moved here from statfile.js
 */
function closeWin(win) {
    var doc = getVirtualPath("/Close.htm");
    win.open(doc, "_self"); win.close();     
}

/*
 * moved here from statfile.js
 */
function getVirtualPath() {
    var l = vertiTop.location;
    return l.protocol + "//" + l.host + l.pathname.substring(0,l.pathname.lastIndexOf("/"));
}
/*
 * moved here from statfile.js
 */
function setVirtualPath(path, appl) {
    if (!appl) appl = "";
    if (path.indexOf("..") == 0) path = path.substring(2);
    if (appl.indexOf("..") == 0) appl = appl.substring(2);
    var search = "",idx = path.indexOf("?");
    if (idx > -1) {
        search = path.substring(idx);
        path = path.substring(0,idx);
    }
    idx = path.lastIndexOf("/");
    if (idx > -1) path = path.substring(idx);
    return getVirtualPath() + appl + path + search;
}

function isMenu() {
	return typeof(vertiTop.menu)=="object";
}

function findVertiTop() {
    try {
        if (this.name == "vertiTop") return this;
        if (this.vertiTop) return this.vertiTop;
        if (this.parent)
        {
            if (this.parent.name == "vertiTop") return this.parent;
            if (this.parent.vertiTop) return this.parent.vertiTop;
        }
        if (opener && opener.vertiTop) { return opener.vertiTop; }
    } catch (e) {}
    return this;
}

/*
In Separate window mode closes child window when user changes father windows location
*/
function closeIfNoFatherWindow() {
    // exceptions in the close rule
    if (typeof vertiTop.px == "object" && typeof vertiTop.px.location.pathname == "string") { // does px window really exist?
        var validLocations = ['statpage.aspx', 'statpagev23.aspx', 'graphlist.aspx', 'graphpage.aspx' , 'statiframe.aspx' , 'statiframev23.aspx' , 'saveshow.asp'];
        var closablePage = true; // page doesn't belong to uncloseable page list
        var fatherWindLoc = vertiTop.px.location.href.toLowerCase();
        for (i = 0; i < validLocations.length; i++) {
            if (fatherWindLoc.indexOf(validLocations[i]) > 0) {
                closablePage = false;
                break;
            }
        }    
        if (closablePage) {
            vertiTop.closeWin(window);
        }
    }    
}

// links to load pages in new window
saveShowLocation = "/Dialog/Saveshow.asp";
graphPageLocation = "/graph/GraphPage.aspx";

function toGraph(owin,doc)
{
    // owin == opener (=hide)
    if (!graph_enabled) return false;
    if (!gappl_enabled) return true; // px-web grafiikka enabloitu
    if (!doc) doc = document;
	var f = doc.forms[0];
    if (typeof(f)=="object") 
    {
        var n = f.noofvar.value;
        var t = setVirtualPath(gdoc,gappl); // huom: graph.js.setVirtualPath()
         t += "?ssid=" + vertiTop.getSessID();
         t += "&lang=" + vertiTop.getLang();
         t += "&matrix=";
         t += (vertiTop.StatPage.Form.varparm) ? getHttpItem("?" + vertiTop.StatPage.Form.varparm,"ma") : f.matrix.value;
         t += "&timeid=";
         t += f.timeid.value;
         t += "&root=";
         t += (vertiTop.StatPage.Form.varparm) ? getHttpItem("?" + vertiTop.StatPage.Form.varparm,"path") : f.root.value;
         t += "&case=";
         t += (vertiTop.StatPage.Location) ? getHttpItem(vertiTop.StatPage.Location,"case"): "db";
            //+ "&selidx=" + escape(getSelForQue());
        if (vertiTop.isGedit())       // using separate window feature
        {
            t += "&Gedit=true";
            vertiTop.menu.setMsel();
            if (vertiTop.menu.isSelcmd()) t += "&Selcmd=" + escape(vertiTop.menu.getSelcmd());
        }
        if (vertiTop.menu.RunInSeparateWindow())        
            doc.location = t;         // using separate window feature                   
        else
        {
            this.vertiTop.px.location = t;                   
        }
    }	 
    return false;
}

function imgType() {
    if (isVml()) return "vml";
    if (isGecko1_8up() || isOpera9_1up()) return "svg";
    return "png";
}

function isSvgCtlInstalled(){
    if (!isSvgCtlAllowed) return false;
    try {
        var asv = new ActiveXObject("Adobe.SVGCtl");
        return true;
    } catch(e){}
    return false;
}

function isMSIE() {
  return navigator.appName == "Microsoft Internet Explorer" 
			 && navigator.userAgent.indexOf("MSIE")>-1;
}

function isMSIE(vers) {
  var r =navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf("MSIE")>-1;
  if (!r) return false;
  if (!vers) return r;
  var ua = navigator.userAgent,idx=ua.indexOf("MSIE")+5;
  ua = ua.substring(idx).split(";")[0];
  return Number(ua) == Number(vers);
}

function isMSIE4to8() {
	if (!isMSIE())return false;
	var ua = navigator.userAgent,idx=ua.indexOf("MSIE")+5;
	ua = ua.substring(idx).split(";")[0];
	return ua > 4 && ua < 9;
}

function isVml(){
	return isMSIE4to8() && !isSvgCtlInstalled();
}

function isOpera9_1up(){ 
var ua = navigator.userAgent;
return navigator.appName == "Opera" && ua.substr(1+ua.indexOf("/"),3)>9.0;
}

function isGecko() {
return navigator.product == "Gecko";
}

function isGecko1_8up() {
if (!isGecko()) return false;
var ua = navigator.userAgent;
if (ua.indexOf("Chrome")>-1) return true;
var i = ua.indexOf("rv:");
if (i == -1) return false;
return ua.substr(i+3,3)>=1.8; // support for svg is since rv:1.8
}

function isBrowserIe6Lower()
{
    var browser=navigator.appName;
    return (browser=="Microsoft Internet Explorer" && typeof document.body.style.maxHeight == "undefined");
}
/*
 * functions embeddedImageCode and linkImageCode are
 * used by showLink() in graphlist.js
*/
function embeddedImageCode(href,title,isrv,x,y){
	href = linkCode(href,isrv);
	var w,h;
	if (!y) {
	 	 w = x = getHttpItem(href,"x");
	 	 h = y = getHttpItem(href,"y");
	 	 w = Number(w) + 0.08 * Number(w); w=w-w%1;
	 	 h = Number(h) + 0.08 * Number(h); h=h-h%1;
	} else {
		 w = "100%";
		 h = "100%";
	}
	var html = '<iframe class="imgctl" src="' + href + '" '
        + 'frameborder="0" scrolling="no" marginwidth="0" marginheight="0" '
        + 'height="' + h + '" width="' + w + '">' + title
        + '</iframe>';
		return html;
}
function linkImageCode(href,title,isrv,x,y){
	href = linkCode(href,isrv);
	var w,h;
	if (!y) {
	 	 w = x = getHttpItem(href,"x");
	 	 h = y = getHttpItem(href,"y");
	 	 w = Number(w) + 0.08 * Number(w); w=w-w%1;
	 	 h = Number(h) + 0.08 * Number(h); h=h-h%1;
	} else {
		 w = "100%";
		 h = "100%";
	}
	href = replaceHttpItem(href,"x","x=" + w);
	href = replaceHttpItem(href,"y","y=" + h);
	var html = '<a class="imglink" href="' + href + '" target="_new">' + title + '</a>';
	return html;
}

function linkCode(href,isrv) {
    var srv = isrv.toLowerCase();
	return href.toLowerCase().replace(".png",".aspx").replace(".svg",".aspx").replace(".vml",".aspx").replace(srv,isrv);
}

function variable() {

    this.data = {};
    this.vars = {} //MKOS

    this.Store = function(sel){
        for (var i in sel) {
            this.data[i] = sel[i];
        }
    }; 
    // MKOS: store sellist to reuse in varvm when returning to StatPage
    this.storeVar = function(sel){
        for (var i in sel) {
            this.vars[i] = sel[i];
        }
    }; 

    this.Length = function() {
        var count = 0;
        for (var i in this.data) count++;
        return count;
    };

    this.list = function(varname) {
        var msg = "";
        for (var i in this[varname]) {
            msg += i + "=" + this[varname][i] + "\n";
        }
        show(varname + ":", msg);
    };

};

function getHttpItem(query,key) {
    // query = http-query
    var i,r = "";
    key = key.toUpperCase();
    query = query.toString();
    if (query.indexOf("#")>-1) {
	     query =query.split("#")[0];
    }
    query += "&";
    i = query.toUpperCase().indexOf("&" + key + "=");
    if (i == -1) i = query.toUpperCase().indexOf("?" + key + "=");
    if (i == -1) return r;
    r = query.substring(i + 2 + key.length);
    r = unescape(r.substring(0,r.indexOf("&")));
    r = r.replace(/\+/g," ");
    return r;
}

function replaceHttpItem(lst,key,itm) {
    //the whole item is replaced or appended, not only value
    lst = unescape(lst);
    var hash = "";
    if (lst.indexOf("#")>-1) {
	     lst =lst.split("#");
	     hash = lst[1];
	     lst = lst[0];
	     }
    var sep,v;
    if (lst.indexOf("&" + key + "=") == -1 && lst.indexOf("?" + key + "=") == -1) {
	     sep = (lst.indexOf("?")>-1) ? "&" : (lst.indexOf("&")>-1) ? "&" : "?";
         if (itm.length>0) lst = lst + sep + itm;
    } 
    else {
	     sep = (lst.indexOf("?" + key + "=")>-1) ? "?" : "&";
         lst = lst.split(sep + key + "=");
	     var idx = lst[1].indexOf("&");
	     itm = (itm.length > 0) ? sep + itm : itm;
	     if (idx > -1) lst = lst[0] + itm + lst[1].substring(idx);
	     else lst = lst[0] + itm; 
	     if (sep == "?" && lst.indexOf("?") == -1) lst = lst.replace("&","?");
    }	
    if (hash.length>0) lst += "#" + hash;	
    return lst;
}

/* moved here from statfile.js */
function getAction(doc) {
    return getHttpItem(doc.location.search,"ACTION");
}

/* moved here from graphpage.js 
 * used by graphpage and statpage
 */
function decodeLtGt(t){
  t=unescape(t);
  t = t.replace(/\$\[/g,"<");
  t = t.replace(/\$\]/g,">");
    
  return t;
}
/* moved here from graphpage.js 
 * used by graphpage and statpage
 */
function encodeLtGt(t){
	t = t.replace(/</g,"$[");
	t = t.replace(/>/g,"$]");
	t = t.replace(/\$\[f/g,"[F");
    t = t.replace(/\$\[l/g,"[L");
    t = t.replace(/\$\[a/g,"[A");
    t = t.replace(/t\$\]/g,"T]");
    t = t.replace(/l\$\]/g,"L]");
    t = t.replace(/\&amp;/g,"&").replace(/\&/g,"&amp;");
    return t;
}


/*
 * to launch Verti stand alone graphics from PX-Web
 * when verti graph is launched from PX-Web's ShowTableHtml2.asp, the method below replaces the orginal function
 */
function LaunchNew(selvalue) 
{
if (selvalue.selectedIndex > 0) {
	var href,oldhref = selvalue.options[selvalue.selectedIndex].value;
	if (oldhref.indexOf("diagramloop.asp")>-1 || oldhref.indexOf("MakeGraph.asp")>-1 ) {
	    var form = document.forms[2];
	    href = "../graph?matrix=" + form["matrix"].value;
	    href += "&timeid=" + form["timeid"].value;
	    if (oldhref.indexOf("MakeGraph.asp")>-1){
	        href += "&lang=" + getHttpItem(oldhref,"PLanguage");
	    } else {
	       href += "&lang=" + getHttpItem(oldhref,"lang");
	    }
	} else {
	    href = oldhref;
	}
	window.open(href);
	selvalue.selectedIndex=0;
	}
}

/*
 * Tool. Moved here from statpage.js
 */   
function showProps(obj, objName) {
   if (!objName) objName="-";
   var result = "";
   for (var i in obj) {
      result += objName + "." + i + " = " + obj[i] + "\n";
   }
   return result;
}

/*
 * Tool. Moved here from statpage.js
 */   
function showForm(fr,form) {
var r,n = "\n";
if (!form) form = 0;
if (fr.document) fr = fr.document;
r = fr.forms[form].name + n;
r += "location:" + fr.location.toString() + n;
r += "action:" + fr.forms[form].action + n;
r += "target:" + fr.forms[form].target + n;
var f = fr.forms[form].elements;
for(var i = 0;i<f.length; i++) {
	 if (f[i].name.substring(0,2) != "__") {
	 		r +="[" + i + "]" + f[i].name;
	 		if (f[i].type == "radio" || f[i].type == "checkbox") if (f[i].id) r += "." + f[i].id ;
			r += ":" + f[i].type;
			if (f[i].text) r += f[i].text;
			if (f[i].type == "radio" || f[i].type == "checkbox"){
			 	 if (f[i].type == "radio") r += "," + f[i].value;
				 r += "=" + f[i].checked;
				 }
		  else if (f[i].value) r += "=" + f[i].value;
	 		r += n;
	 } 
	 else r +="[" + i + "]" + f[i].name + ":hidden .NET field" + n;
}
show(r);
} 

function getDocHeight(D) {
    if (!D) D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}
function getDocWidth(D) {
    if (!D) D = document;
    return Math.max(
        Math.max(D.body.scrollWidth, D.documentElement.scrollWidth),
        Math.max(D.body.offsetWidth, D.documentElement.offsetWidth),
        Math.max(D.body.clientWidth, D.documentElement.clientWidth)
    );
}


