window.onerror = function (e) {
 return true;
}

/* hypp&auml;&auml; pois ifreimist&auml; */

if (top.location != location)
      top.location.href = document.location.href;

/* ---------------- siirr&auml; n&auml;m&auml; header.jsp:hen tms. ------------------------*/

/*admin tila */
document.admin = true;

/* k&auml;&auml;nn&ouml;kset*/
document.translations = [];
document.translations['save_changes']  = "Tallennetaanko muutokset?";
document.translations['delete'] = "Delete";
document.translations['rename'] = "Rename";
document.translations['add'] = "Add";
document.translations['move_up'] = "Move Up";
document.translations['move_down'] = "Move Down";
document.translations['move_to_root'] = "Move To Root";
document.translations['move_to'] = "Move To...";
document.translations['really_delete_category'] = "Really delete category : ";
document.translations['cant_move_below_itself'] = "Can't move category below itself!";
document.translations['move category'] = "Move category : ";

/* ---------------- /siirr&auml; n&auml;m&auml; header.jsp:hen tms. ------------------------*/


/* --------------- cookie handling ------------------------------------------*/





    function getCookie(name)
    {
      var bikky = document.cookie;
      var index = bikky.indexOf(name + "=");
      if (index == -1) return null;
      index = bikky.indexOf("=", index) + 1; // first character
      var endstr = bikky.indexOf(";", index);
      if (endstr == -1) endstr = bikky.length; // last character
      return unescape(bikky.substring(index, endstr));
    }

    function addCookie(name, value)
    {
      //alert(name + "=" + value);
      document.cookie = name+"="+value+";EXPIRES=Mon, 03-12-2040;";
    }


    function removeCookie(name)
    {
      document.cookie = name+"=;EXPIRES=mON, 12-12-1973;";
    }


      var cookieName = "catView";
      function useView(catId, mode)
      {
        var cookieValue = getCookie(cookieName);
        //alert(mode);
        if (cookieValue == '' || cookieValue == null)
        {
          if (mode != 'undefined' )
          {
            addCookie(cookieName, catId+'='+mode);
          }
        }
        else
        {
          if ( cookieValue.indexOf(catId+'=') == -1 )
          {
            if (mode != 'undefined')
            {
              cookieValue = cookieValue+'|'+catId+'='+mode;
              addCookie(cookieName, cookieValue);
            }
          }
          else
          {
            var newValue = catId+'='+mode;
            cookieValues = cookieValue.split('|');
            cookieValue = '';
            for (var i = 0; i < cookieValues.length; i++)
            {
              var value = cookieValues[i].split('=');
              var cat = value[0];
              var curmode = value[1];
              if (cat != catId)
              {
                if ( curmode != 'undefined' )
                cookieValue = cookieValue+'|'+cat+'='+curmode;
              }
              else
              {
                cookieValue = cookieValue+'|'+newValue;
              }
            }
            removeCookie(cookieName);
            addCookie(cookieName, cookieValue);
          }
        }
        //alert(getCookie(cookieName));
      }

      function buttonAction(command)
      {
        document.goTo.mode.value = command;
        document.goTo.submit();
      }


/* ----------------------- j tree v 0.1 -------------------------------------*/

	var jRoots = []; //JRoot stack

	function JRoot()
	{
		this.items = []; //item stack
		this.idN = jRoots.length; //save this index
		jRoots.push(this);

		this.root = new Branch(this.idN, this, 0, "ROOT", "/");
		this.curBra = this.root;
	}

	JRoot.prototype.addItem = function(depth, name, href, isOpen, propertyObj)
	{
		if (depth == this.curBra.depth)
		{
			var parent = this.curBra.parent;
		}
		else if (depth > this.curBra.depth)
		{
			var parent = this.curBra;
		}
		else if (depth < this.curBra.depth)
		{
			var parent = this.curBra;
			while (parent.depth >= depth)
			{
				parent = parent.parent;
			}
		}

		this.curBra = parent.addBranch(this.idN, parent, depth, name, href, isOpen);
		this.items[this.curBra.branchIdN].properties = propertyObj;
	}

	JRoot.prototype.swzBra = function (img,braId)
	{
		this.items[braId].swz(this.items[braId].isOpen^=1);
		if (this.items[braId].isOpen == 0)
    {
      this.isOpen = false;
			img.src = "/pics/icon-open.gif";
		}
    else
    {
      this.isOpen = true;
			img.src = "/pics/icon-close.gif";
	  }
  }

	function Branch(treeIdN, parent, depth, name, href, isOpen)
	{
		this.branches = [];
		this.parent = parent;
		this.depth = depth;
		this.name = name;
		this.href = href;
    this.isOpen = isOpen;
		this.treeIdN = treeIdN;
		this.branchIdN = jRoots[treeIdN].items.length;
		jRoots[treeIdN].items.push(this);
	}

	Branch.prototype.swz = function (onOff)
	{
		for (var i = 0; i < this.branches.length; i++)
		{
			if (onOff == 0)
			{
				this.branches[i].swz(onOff);
				this.isOpen = 0;
			}
			var element = document.getElementById("tree_"+this.treeIdN+"_item_"+this.branches[i].branchIdN);
			element.style.display = onOff ? "block" : "none";
		}
	}

	Branch.prototype.addBranch = function (treeIdN, parent, depth, name, href, isOpen)
	{
		this.branches.push( new Branch(treeIdN ,parent, depth, name, href, isOpen) );
		return (this.branches[this.branches.length-1])
	}

	Branch.prototype.write = function (p)
	{
    if (! document.getElementById("menuDiv"))
    {
      /* item valikon HTML */
      document.writeln(
                       '<ul id="menuDiv" onmouseout="menuAct.timeout()" onmouseover="menuAct.stay()">'+
                       '<li onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><a href="javascript:menuAct.renameCat()"><img src="/pics/contentmanager/paivitys-hakemiston-ominaisuudet.gif" border="0" width="13" height="13" align="absmiddle" hspace="4">'+document.translations['rename']+'</a></li>'+
                       '<li onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><a href="javascript:menuAct.addCat()"><img src="/pics/contentmanager/paivitys-lisaa-moduuli.gif" border="0" style="background-image:url(/pics/contentmanager/ImageBank/icon.gif)" align="absmiddle" hspace="4">'+document.translations['add']+'</a></li>'+
                       '<li onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><a href="javascript:menuAct.moveUp()"><img src="/pics/contentmanager/paivitys-nuoli-ylos.gif" border="0" width="13" height="13" align="absmiddle" hspace="4">'+document.translations['move_up']+'</a></li>'+
                       '<li onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><a href="javascript:menuAct.moveDown()"><img src="/pics/contentmanager/paivitys-nuoli-alas.gif" border="0" width="13" height="13" align="absmiddle" hspace="4">'+document.translations['move_down']+'</a></li>'+
                       '<li onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><a href="javascript:menuAct.moveTo()"><img src="/pics/contentmanager/paivitys-siirra.gif" border="0" width="13" height="13" align="absmiddle" hspace="4">'+document.translations['move_to']+'</a></li>'+
                       '<li onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><a href="javascript:menuAct.deleteCat()"><img src="/pics/contentmanager/paivitys-poista.gif" border="0" width="13" height="13" align="absmiddle" hspace="4">'+document.translations['delete']+'</a></li>'+
                       '</ul>');

    //  '<tr onmouseover="menuAct.hoverIn(this)" onmouseout="menuAct.hoverOut(this)"><td><a href="javascript:menuAct.moveToRoot()"><img src="/pics/contentmanager/paivitys-siirra.gif" border="0" width="13" height="13" align="absmiddle" hspace="4">'+document.translations['move_to_root']+'</a></td></tr>'+

    }
		var bold = '';
		if (p.depth > 0)
		{
			if (p.depth > 1 && !p.parent.isOpen)
				var opn = 'none';
			else
			{
				var opn = 'block';
			}

			if (p.branches.length == 0)
			{
				var opener = '';
		        var icon = 'icon-empty.gif';
			}
			else
			{
				var opener = 'onclick="jRoots['+p.treeIdN+'].swzBra(this,'+p.branchIdN+')"';
				var icon = 'icon-open.gif';
			}



		    if (p.isOpen && p.branches.length)
			{
       			var icon = 'icon-close.gif';
			}

			document.writeln('<div class="category'+p.depth+'" id="tree_'+p.treeIdN+'_item_'+p.branchIdN+'" style="display:'+opn+';">'+
							 '<img src="/pics/'+icon+'" width="16" height="16" alt="" border="0" align="left" '+opener+'> <div style="padding:0px 6px 2px 20px;"><a class="navi" href="'+p.href+'">'+p.name+'</a></div>');

      if (document.admin)
      {
        document.writeln('<a href="#" class="menuHover" onclick="menuAct.show(this,jRoots['+p.treeIdN+'].items['+p.branchIdN+'])"><img src="/pics/ambientia/category-edit.gif" width="35" height="17" alt="" border="0"></a>');

      }

			document.writeln('</div>'	);
		}

		for(var i = 0; i < p.branches.length; i++)
		{
			var c = p.branches[i];
			this.write(c);
		}

	}

  Branch.prototype.checkRelationIsParent = function(bra)
  {
    var cbra = bra;
    while (cbra.parent)
    {
      if (cbra.parent == this) return true;
      cbra = cbra.parent;
    }

    return false;
  }


  /* hovers */
  function dragOver(o)
  {
    o.style.backgroundColor = "";
  }

  function dragOut(o)
  {
    o.style.backgroundColor = "";
  }



  //auml korjattu confirm box
  function aumlConfirm(q)
  {
    q = q.replace(/&auml;/g,"&auml;")
    q = q.replace(/&Auml;/g,"Ä")
    q = q.replace(/&Ouml;/g,"Ö")
    q = q.replace(/&ouml;/g,"&ouml;")
    q = q.replace(/&Aring;/g,"Å")
    q = q.replace(/&aring;/g,"å")
    return confirm(q);
  }

  /* Item valikon toiminnot */
  var menuAct =
  {
      actionTarget : null,
      renameCat : function ()
      {
        //nime&auml;minen
        document.location.href = "./?mode=editCategory&c="+this.actionTarget.properties.from;
      },
      deleteCat : function ()
      {
        if (aumlConfirm(document.translations['really_delete_category']+this.actionTarget.name))
        {
          //deletointi
		      document.forms['moveCat'].mode.value = 'removeCategory';
    	      document.forms['moveCat'].id.value = this.actionTarget.properties.from;
		      document.forms['moveCat'].url_redirect.value = this.actionTarget.parent.href;
		      document.forms['moveCat'].submit();
        }
      },
      addCat : function ()
      {
		  	  //AMBIMG-221
       		  document.location.href = this.actionTarget.href+"?mode=addCategory&c="+this.actionTarget.properties.from;
      },
      moveUp : function ()
      {
        //siirto yl&ouml;sp&auml;in
		    document.forms['moveCat'].mode.value = 'changeCategoryOrdinal';
    	  document.forms['moveCat'].id.value = this.actionTarget.properties.from;
		    document.forms['moveCat'].updown.value = 'true';
		    document.forms['moveCat'].url_redirect.value = this.actionTarget.href;
		    document.forms['moveCat'].submit();
      },
      moveDown : function ()
      {
        //siirto alasp&auml;in
		    document.forms['moveCat'].mode.value = 'changeCategoryOrdinal';
    	  document.forms['moveCat'].id.value = this.actionTarget.properties.from;
		    document.forms['moveCat'].updown.value = 'false';
		    document.forms['moveCat'].url_redirect.value = this.actionTarget.href;
		    document.forms['moveCat'].submit();
      },
      moveTo : function ()
      {
        document.location.href = this.actionTarget.href+"?mode=moveCategory&id="+this.actionTarget.properties.from;
      },
      moveToRoot : function ()
      {
        //siirto juureen
		    document.forms['moveCat'].id.value = this.actionTarget.properties.from;
		    document.forms['moveCat'].parentId.value = '1';
		    document.forms['moveCat'].submit();
      },
      // hoverit
      hoverIn : function (o)
      {
         o.style.backgroundColor = "";
      },
      hoverOut : function (o)
      {
        o.style.backgroundColor = "";
      },
      // avautuminen
      show : function ( a, itm)
      {
        var ag = DHTMLBase.getGeometry(a);
        var menuDiv = document.getElementById("menuDiv");
        this.actionTarget = itm;
        document.body.appendChild(menuDiv);
        menuDiv.style.top = ag.y+"px";
        menuDiv.style.left = (ag.x+ag.width)+"px";
        menuDiv.style.display = "block";
      },
      // katoaminen
      timeout : function ()
      {
        if (this.hideTimer) clearTimeout(this.hideTimer);
        this.hideTimer = setTimeout('menuAct.hide()',1000);
      },
      stay : function ()
      {
        if (this.hideTimer) clearTimeout(this.hideTimer);
      },
      hide : function ()
      {
        if (this.hideTimer) clearTimeout(this.hideTimer);
         var menu = document.getElementById("menuDiv");
         menu.style.display = "none";
      }
  }


	/* drag functions */
	function dragStart(treeId, itemId)
	{
		if (document.dragElement) return;
		var element = document.getElementById('tree_'+treeId+'_item_'+itemId);
		element.className = "dragNavi";
		element.offX= 192;
		element.offY= 8;
		document.dragElement = element;
		document.fromTree = treeId;
		document.fromItem = itemId;

		document.old_onmousemove = document.onmousemove; //save old handler
		document.onmousemove = function (e)
		{
			DHTMLBase.setupEventObject(e);

      if (document.overDiv)
        dragOut(document.overDiv);

      document.overDiv = getItemAt(window.event.clientX,window.event.clientY);

      if (document.overDiv)
        dragOver(document.overDiv);

			document.dragElement.style.left = (window.event.clientX - document.dragElement.offX) + "px";
			document.dragElement.style.top = (window.event.clientY - document.dragElement.offY) + "px";
		};

		document.old_onmouseup = document.onmouseup; //save old handler

		document.onmouseup = function (e)
		{
			DHTMLBase.setupEventObject(e);
			document.onmousemove = document.old_onmousemove; //restore old handler
			document.onmouseup = document.old_onmouseup; //restore old handler
			var droppedOn = getItemAt(window.event.clientX,window.event.clientY)
			if (document.dragElement && droppedOn)
			{
				var tmp = droppedOn.id.split("_");
				document.toTree = parseInt(tmp[1]);
				document.toItem = parseInt(tmp[3]);
        var fromItem = jRoots[document.fromTree].items[document.fromItem];
        var toItem = jRoots[document.toTree].items[document.toItem];

        if (fromItem.checkRelationIsParent(toItem))
        {
          alert(document.translations['cant_move_below_itself']);
        }
        else if (aumlConfirm (document.translations['move_category']+fromItem.name+" -> "+toItem.name))
        {
          /* l&auml;hetet&auml;&auml;n arvot */
          document.forms['moveCat']['id'].value = fromItem.properties.from;
          document.forms['moveCat']['parentId'].value = toItem.properties.from;
          document.forms['moveCat']['url_redirect'].value = toItem.href;
          document.forms['moveCat'].submit();
			  }
      }
			document.dragElement.className = "navi";
			document.dragElement.style.top = "";
			document.dragElement.style.left = "";
			document.dragElement = null;
		}
	}

	function getItemAt(x,y)
	{
		var n = document.getElementById("tree_"+document.fromTree+"_item_1");
		var i = 1;
		while (n)
		{
			if (n != document.dragElement)
			{
				var g = DHTMLBase.getGeometry(n);
				if ( (g.left < x) && (g.top < y) && (g.right > x) && (g.bottom > y))
				return(n);
			}
			i ++;
			n = document.getElementById("tree_"+document.fromTree+"_item_"+i);
		}
	}

  var saveButtonClicked = false;

  function checkSaving()
  {
    if (!saveButtonClicked && document.touched)
    {
    if (confirm("Tallennetaanko muutokset?"))
    {
      var form = document.getElementById("editObject");
      form.submit();
    }
    else
    {
      return true;
    }
    }
    else
    {
      return true;
    }
  }


    function checkDating(f) {
      var ordOk = false, valOk = false ,n = f.name.split("_");
      f.value = parseInt(f.value);

      switch (n[1]) {

        case "year":
          ordOk = true;
          if (f.value > 0) valOk = true;
          break;
        case "month":
          if (f.form[n[0]+'_year'].value != "") ordOk = true;
          if (f.value > 0 && f.value < 13) valOk = true;
          break;
        case "day":
          if (f.form[n[0]+'_month'].value != "") ordOk = true;
          if (f.value > 0 && f.value < 32) valOk = true;
          break;
        case "hour":
          if (f.form[n[0]+'_day'].value != "") ordOk = true;
          if (f.value > -1 && f.value < 24 ) valOk = true;
          break;
        case "minute":
          if (f.form[n[0]+'_hour'].value != "") ordOk = true;
          if (f.value > -1 &&  f.value < 61) valOk = true;
          break;
      }

        if (!valOk || !ordOk)
          f.value = "";
        if (!valOk)
          alert ("Virheellinen arvo");
        if (!ordOk)
          alert ("T&auml;yt&auml; vasemmalta alkaen");
    }


function opnLay(id) {
  var i,p,d = document.getElementById(id);
  scnBul(document.body,"hidden",d);
  d.style.display = "block";
  d.style.left = ((document.body.clientWidth - d.offsetWidth)/2)+"px";
  d.style.top = ((document.body.clientHeight - d.offsetHeight)/2)+document.body.scrollTop+"px"; }

function clsLay(id) {
  var d = document.getElementById(id);
  scnBul(document.body,"visible",d);
  d.style.display = "none"; }

function scnBul(p,v,d) {
  for(var i = 0; i < p.childNodes.length; i++) {
    if (p.childNodes[i].nodeName == "SELECT")
    {
        if (!inLayer(p.childNodes[i],d))
          p.childNodes[i].style.visibility = v;
    }
    scnBul(p.childNodes[i],v,d); } }

function inLayer(c,d) {

   while (c.parentNode) {
     c = c.parentNode;
     if (c.nodeName == "DIV" && d == c)
     	return true;
   }
   return false;
 }


document.touched = false;

     function touch() {
      if(this.oldOnChange) this.oldOnChange();
       document.touched = true;
    }

    function setFormTouchWatch() {
      for(var i = 0; i < document.forms.length; i++) {
        var f = document.forms[i];
        for (var j = 0; j < f.length; j++) {
          if (f[j].onchange) f[j].oldOnChange = f[j].onchange;
          f[j].onchange = touch;
        }
      }
    }


//blokataan virheilmoitukset


function suurenna(id) {
        scnBul(document.body,"hidden")
	var h = window.innerHeight | document.body.clientHeight;
	var w = 600; /*window.innerWidth | document.body.clientWidth;*/
	document.getElementById("minimize").style.display = "block";
	var e = document.getElementById(id);
	e.style.position = "absolute";
	e.style.top = "0px";
	e.style.left = "10px";
	e.style.width = w+"px";
	e.style.height = h+"px";
	e.style.backgroundColor = "#fff";
}
function pienenna(id) {
	scnBul(document.body,"visible")
	document.getElementById("minimize").style.display = "none";
	var e = document.getElementById(id);
	e.style.position = "";
	e.style.width = "";
	e.style.height = "";
}


window.onerror = function (e) { return false; }
