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 isSvgCtlAllowed = false; // Prevents use of Adobe SVG plugin in IE 

var vertiTop = findVertiTop();

function show(item){
// util
    if (vertiTop.test) {
        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("/graph/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.asp";

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()
            /*            
            + "?lang=" + vertiTop.getLang()
            + "&matrix=" + escape(f.matrix.value)
            + "&timeid=" + escape(f.timeid.value)
            + "&root=" + escape(f.root.value)
            + "&case=" + getHttpItem(vertiTop.StatPage.Location,"case");
            */
         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;
}

// global plugin variables
var pluginspage = "www.adobe.com/svg/viewer/install/";
var pluginstype = "image/svg+xml";
var pluginsstyle = "margin:0px;";
var pluginswidth = "100%";
var pluginsheight = "95%";
/*
function pictureCode(href,x,y) {
	if (isSvgCtlInstalled()) return embedCode(href,x,y);
  if (!y) {
		 y = getHttpItem(href,"y");				 
		 y = 0.95*y;
		 x = 1.35*y;
		 y = y-y%1;
		 x = x-x%1;
	}	 
	href = replaceHttpItem(href,"x","x=" + x);
	href = replaceHttpItem(href,"y","y=" + y);
	return svgLinkCode(href,x,y);
}

function embedCode(href,w,h){
if (!w) {
	 w=pluginswidth;
	 h=pluginsheight;
	 }
var plg = (pluginspage.length>0) ? ' pluginspage="' + pluginspage + '">\n' : '';
var html =  '<embed id="svgctl" name="svgctl"'
		+ ' width="' + w + '" height="' + h + '"\n'
		+ ' type="' + pluginstype + '" style="' + pluginsstyle + '"\n'
		+ ' src="' + href + '" \n'
		+ plg
		+ '</embed>';
return html;
} 
function objectCode(href,w,h) {
if (!w) {
	 w=pluginswidth;
	 h=pluginsheight;
	 }
var html = '<object id="svgctl0"\n type="' + pluginstype + '"\n'
		+ ' width="' + w + '" height="' + h + '"\n'
		+ ' data="' + href + '">\n'		 
		+ '<p>Your browser does not support svg graphics'
		+ '</object>\n'
    + '<![endif]>\n'; 
return html;
}

function imgCode(href,x,y) {
// imgCode for svgframe
href = href.replace(".svg",".png");
// adjust img size to svgframe
if (!y) {
	 y = getHttpItem(href,"y");
	 x = 1.35*y;
	 x = x-x%1;
	 }	 
return '<img src="'	+ href + '"\n alt="' + getHttpItem(href.toLowerCase(),"ifile") 
		+ '"\n width="' + x + '" height="' + y + '"/>\n';
}	
*/
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 isMSIE4up() {
	if (!isMSIE())return false;
	var ua = navigator.userAgent,idx=ua.indexOf("MSIE")+5;
	return ua.substr(idx,1)>4;
}

function isVml(){
	return isMSIE4up() && !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");
}
/*
function svgLinkCode(href,x,y){
	var png = href.replace(".svg",".png");
	var vml = href.replace(".svg",".vml");
	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 = pluginswidth;
		 h = pluginsheight;
	}
	var alt = getHttpItem(href.toLowerCase(),"ifile");
	var html = '<!--[if IE]>\n'
        //+ '<iframe src="' + vml + '" height="' + h + '" width="' + w + '">\n'
        + '<iframe id="vmlctl" src="' + vml + '"\n'
        + 'frameborder="0" scrolling="no" marginwidth="0" marginheight="0" '
        + 'height="' + h + '" width="' + w + '">'
        + '</iframe>'
        + '<![endif]-->\n'
        + '<![if !IE]>\n'
	    + '<object id="svgctl" name="svgctl"'
		+ ' width="' + w + '" height="' + h + '"\n'
		+ ' type="' + pluginstype + '" style="' + pluginsstyle + '"\n'
		+ ' data="' + href + '">\n'
		+ ' <param name="src"\n'
		+ ' value="' + href + '">\n'
    	+ ' <object\n type="image/png"\n'
		+ ' width="' + x + '" height="' + y + '"\n'
		+ ' data="' + png + '">\n'		 
		+ '</object>\n'
		+ '<img src="' + png + '"\n'
 		+ 'alt="' + alt +'"\n'
 		+ 'width="' + x + '" height="' + y + '"/>\n'
		+ '</object>\n'
        + '<![endif]>\n';
		return html;
}
*/
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 = pluginswidth;
		 h = pluginsheight;
	}
	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 = pluginswidth;
		 h = pluginsheight;
	}
	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 {
  v = getHttpItem(lst,key);
  if (lst.indexOf(" ")> -1) v = v.replace(/ /g,"+");
	if (itm.length==0) { 
		 sep = (lst.indexOf("?" + key + "=")>-1) ? "?" : "&";
		 lst = lst.replace(sep + key + "=" + v, "");
		 if (sep == "?") lst = lst.replace("&","?"); 
	}
	else { 	lst = lst.replace(key + "=" + v, itm);}
}	
if (hash.length>0) lst += "#" + hash;	
return lst;
}

/* moved here from statfile.js */
function getAction(doc) {
    return getHttpItem(doc.location.search,"ACTION");
}

// when 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);
} 

