function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
  d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function setsearchdisplay(disp)
{
	//alert("setsearchdisplay");
  o = MM_findObj('searchlayer');
  o2 = MM_findObj('searchframe');
  if (document.all || document.getElementById) {
    step = 2;
    maxheight = 100;
    if (disp == 'block')
    {
      o.style.height = '0px';
      o2.height = 0;
      o.style.display = disp;

      for (i=0;i<maxheight+step;i+=step)
      {
        o.style.height = '' + i + 'px';
        o2.height = i;
        pausecomp(5);
      }

    }
    else
    {
      o.style.height = maxheight + 'px';
      o2.height = maxheight;
      for (i=maxheight;i>step*(-1);i-=step)
      {
        o.style.height = '' + i + 'px';
        o2.height = i;
        pausecomp(5);
      }
      o.style.display = disp;
    }
  } else if (document.layers) {
    o.display = disp;
  }
}

function pausecomp(millis)
{
  var date = new Date();
  var curDate = null;

  do { curDate = new Date(); }
  while(curDate-date < millis);
}

function searchMouseClick(id, v)
{
  var divindex = id.substr(1);
	/*window.parent.document.searchasd.cntwindex.value = divindex;
  window.parent.document.searchasd.search.value = v;
  window.parent.document.searchasd.submit();*/
	document.searchasd.cntwindex.value = divindex;
  document.searchasd.search.value = v;
  document.searchasd.submit();
}

function searchBeforeSubmit()
{
	//alert("searchBeforeSubmit");
  var divindex = document.searchasd.cntwindex.value;

  if(divindex != -1)
  {
    var div = window.searchframe.document.getElementById('W'+ divindex);
    if(div != null)
    document.searchasd.search.value = div.title;
  }
  else
  {
    document.searchasd.search.value = document.searchasd.searchinput.value;
  }

  return true;
}

function searchOnLoad(sText)
{
  if(sText != '') document.searchasd.searchinput.focus();

	//commentezve volt
  /*window.searchframe.document.wordform.word.value=sText;
  window.searchframe.document.wordform.submit();*/
	//wordform.word.value=sText;
	
	//document.getElementById('wform_word').value=sText;
  
  //document.wordform.submit();
}

function searchframeOnLoad()
{

  if(window.parent.document.searchasd.reloadsearchframe.value != 1)
  {
    window.parent.document.searchasd.cntwindex.value = -1;
    window.parent.document.searchasd.reloadsearchframe.value = 0;
  }

  var divindex = window.parent.document.searchasd.cntwindex.value;
  var div      = document.getElementById('W'+(divindex));

  if(div != null)
  {
    div.className = "searchwordactive";
  }
}


function searchKeyUp(evt,sText) {
	//alert("searchKeyUp");
  /* if (document.layers) {
  var oLayer;
  if(parentID){
  oLayer = eval('document.' + parentID + '.document.' + ID + '.document');
  }else{
  oLayer = document.layers[ID].document;
  }
  oLayer.open();
  oLayer.write(sText);
  oLayer.close();
  }
  else if (parseInt(navigator.appVersion)>=5&&navigator.appName=="Netscape") {
  document.getElementById(ID).innerHTML = sText;
  }
  else if (document.all) document.all[ID].innerHTML = sText;
  */

  evt = evt ? evt : window.event;

  switch(evt.keyCode)
  {
    case 13: // enter
    case 37: // jobbra
    case 39: // balra
    break;

    case 38: // fel

    var olddivindex = document.searchasd.cntwindex.value;
    var divindex    = document.searchasd.cntwindex.value;
    
		divindex--;

    /*var olddiv = window.searchframe.document.getElementById('W'+(olddivindex));
    var div    = window.searchframe.document.getElementById('W'+(divindex));*/
		
		var olddiv = document.getElementById('W'+(olddivindex));
    var div    = document.getElementById('W'+(divindex));
		
		if(div != null && olddiv != null)
    olddiv.className = "searchwordinactive";

    if(div != null)
    {
      div.className = "searchwordactive";
      document.searchasd.cntwindex.value--;
    }
    break;

    case 40: // le
		
    var olddivindex = document.searchasd.cntwindex.value;
    var divindex    = document.searchasd.cntwindex.value;
    divindex++;
		
		if (olddivindex=="") {
			olddivindex=0;
		}
		/*var olddiv = window.searchframe.document.getElementById('W'+(olddivindex));
    var div    = window.searchframe.document.getElementById('W'+(divindex));*/
		
		var olddiv = document.getElementById('W'+(olddivindex));
    var div    = document.getElementById('W'+(divindex));
		
		
		
    if(div != null && olddiv != null)
    olddiv.className = "searchwordinactive";

    if(div != null)
    {
      div.className = "searchwordactive";
      document.searchasd.cntwindex.value++;
    }
    break;

    default:
    sText = trimAll(sText);
    document.searchasd.reloadsearchframe.value = 0;
    /*window.searchframe.document.wordform.word.value=sText;*/
    // document.getElementById('wform_word').value=sText;
    //if (sText.length>3)
    //{
      /*document.wordform.submit();*/
			/*window.searchframe.document.wordform.submit();*/
    //}
    break;
  }

}

function leftTrim(sString)
{
  while (sString.substring(0,1) == ' ')
  {
    sString = sString.substring(1, sString.length);
  }
  return sString;
}

function rightTrim(sString)
{
  while (sString.substring(sString.length-1, sString.length) == ' ')
  {
    sString = sString.substring(0,sString.length-1);
  }
  return sString;
}

function trimAll(sString)
{
  while (sString.substring(0,1) == ' ')
  {
    sString = sString.substring(1, sString.length);
  }
  while (sString.substring(sString.length-1, sString.length) == ' ')
  {
    sString = sString.substring(0,sString.length-1);
  }
  return sString;
}



// randomize html tags by class
function randomorder_engine(tagname) {
  this.tagName = tagname;
}
randomorder_engine.prototype={
  tagholders:new Object(),
  masterclass: "randomordercontent",

  init:function(){
    if (!document.getElementById)
    return
    var alltags=document.getElementsByTagName(this.tagName)
    var randomcontentsearch=new RegExp(this.masterclass+"\\s+(group\\d+)", "i") //check for CSS class="randomcontent groupX" (x=integer)
    for (var i=0; i < alltags.length; i++){
      if (randomcontentsearch.test(alltags[i].className)){
        if (typeof this.tagholders[RegExp.$1]=="undefined"){ //if object to hold this group of tags doesn't exist yet
          this.tagholders[RegExp.$1]=new Object() //create object
          this.tagholders[RegExp.$1].ref=[] //create array to hold each tag within group
          this.tagholders[RegExp.$1].contents=[] //create array to hold each tag's content within group
        }
        this.tagholders[RegExp.$1].ref.push(alltags[i]) //add this tag to the array
        temp = []
        temp.push(alltags[i].innerHTML)
        // tag's attributes
        temp.push(alltags[i].selected)
        temp.push(alltags[i].value)
        this.tagholders[RegExp.$1].contents.push(temp) //add this tag's content to the array
      }
    }
    this.scrambleorder()
  },
  scrambleorder:function(){
    for (group in this.tagholders){ //loop thru each array within object
      this.tagholders[group].contents.sort(function() {return 0.5 - Math.random()}) //scramble contents array
      for (var i=0; i < this.tagholders[group].ref.length; i++){
        this.tagholders[group].ref[i].innerHTML=this.tagholders[group].contents[i][0]
        this.tagholders[group].ref[i].selected=this.tagholders[group].contents[i][1]
        this.tagholders[group].ref[i].value=this.tagholders[group].contents[i][2]
      }
    }
  }
}
// call randomize
// randomorder = new randomorder_engine("option")
// randomorder.init()


// oldalso scroll
function tzscroll() {

  var dragging = false;
  var timeoutId = 0;
  var tzx;
  var tzy;
  var tzscrollpane = document.getElementById("tzscrollpane");
  var tzscrollpane2 = document.getElementById("tzscrollpane2");
  if ( document.all )
  {
    tzscrollpane.onmousedown = function(){
      if (timeoutId) window.clearTimeout(timeoutId);
      var e=arguments[0]||event;
      var x;
      var y;
      if (document.documentElement.scrollLeft==0)
      x=document.body.scrollLeft+e.clientX;
      else
      x=document.documentElement.scrollLeft+e.clientX;
      if (document.documentElement.scrollTop==0)
      y=document.body.scrollTop+e.clientY;
      else
      y=document.documentElement.scrollTop+e.clientY;

      //alert(document.body.scrollTop);

      tzscrollpane.onmousemove=function(){
        scrollTo(x-e.clientX, y-e.clientY);
        if (timeoutId) window.clearTimeout(timeoutId);
        timeoutId = window.setTimeout(iestopDragScroll,100);
        return false;
      }
      tzscrollpane.onmouseup=function(){
        tzscrollpane.onmousemove=null;
      }
      return false;
    }
    tzscrollpane2.onmousedown = function(){
      if (timeoutId) window.clearTimeout(timeoutId);
      var e=arguments[0]||event;
      var x;
      var y;
      if (document.documentElement.scrollLeft==0)
      x=document.body.scrollLeft+e.clientX;
      else
      x=document.documentElement.scrollLeft+e.clientX;
      if (document.documentElement.scrollTop==0)
      y=document.body.scrollTop+e.clientY;
      else
      y=document.documentElement.scrollTop+e.clientY;

      //alert(document.body.scrollTop);

      tzscrollpane2.onmousemove=function(){
        scrollTo(x-e.clientX, y-e.clientY);
        if (timeoutId) window.clearTimeout(timeoutId);
        timeoutId = window.setTimeout(iestopDragScroll,100);
        return false;
      }
      tzscrollpane2.onmouseup=function(){
        tzscrollpane2.onmousemove=null;
      }
      return false;
    }
    function iestopDragScroll(){
      tzscrollpane.onmousemove=null;
      tzscrollpane2.onmousemove=null;
    }
  }
  else {
    tzscrollpane.addEventListener("mousedown",startDragScroll,false);
    tzscrollpane.addEventListener("mouseup",stopDragScroll,false);
    tzscrollpane.addEventListener("mouseout",stopDragScroll,false);//különben elég idegesítő működése van, ha a mouseup nem fut le.
    tzscrollpane.addEventListener("mousemove",dragScroll,false);
    tzscrollpane2.addEventListener("mousedown",startDragScroll,false);
    tzscrollpane2.addEventListener("mouseup",stopDragScroll,false);
    tzscrollpane2.addEventListener("mouseout",stopDragScroll,false);
    tzscrollpane2.addEventListener("mousemove",dragScroll,false);
  }

  // non ie
  function startDragScroll(e){
    if ((e.button == 0  ||
    ((e.target instanceof HTMLImageElement) && (e.target.tagName != 'A')))
    ) {
      if (timeoutId) { window.clearTimeout(timeoutId);
      }
      dragging=e;
    }
  }

  function stopDragScroll(e){
    dragging=false;
  }

  function dragScroll(e) {
    if (dragging) {
      window.scrollBy((dragging.clientX-e.clientX),(dragging.clientY-e.clientY));
      dragging = e;
      e.preventDefault();
      e.stopPropagation();
      if (timeoutId) { window.clearTimeout(timeoutId); }
      //            timeoutId = window.setTimeout(stopDragScroll,100);
    }
  }
}


function ifEnter(field,event,actionstring) {
  var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  if (theCode == 13){
    eval(actionstring);
    return false;
  }
  else
  return true;
}


/* **************************/
/* feladatsorok lapozasahoz */
/* **************************/
function problemsresults(command)
{
  /*TODO: filled tömb!, function név?*/
  var isempty = false;
  for (i=0;i<filled.length;i++)
  {
    if (filled[i] == 0)
    isempty = true;
  }
  if (isempty)
  if (!confirm("#L:NOTFILLEDPROBLEMS#"))
  return;
  document.problem.cmd.value = command;
  document.problem.submit();
}

function hide(pageid)
{
//  alert('nemkell');
  var e;
  e = document.getElementById(pageid);
  e.style.display = 'none';
//  $('#'+pageid).css({display:'block',height:'1px',overflow:'hidden'});
//   $('#'+pageid).css({left:'-5000px'});
}

function show(pageid)
{
//  alert('nemkell2');
  var e;
  e = document.getElementById(pageid);
  e.style.display = 'block';
}

function show_all_hidden_parent(id) {
  var rejtett=new Array();
  var muta=$(id);
  while (muta.parent().length) {
//    if (!muta.is(':visible')) {
    if (muta.css('display') == 'none') {
      rejtett.push(muta);
    }
    muta = muta.parent();//rekurzivan
  }
  for (var i = 0; i < rejtett.length; i++) rejtett[i].show();
  return rejtett;
}

function hide_all_hidden_parent(rejtett) {
  for (var i = 0; i < rejtett.length; i++) {
    if (rejtett[i].is(':visible')) rejtett[i].hide();//a feltétel azért kell, mert lehet, hogy közben eltűnt amúgy is, pl css classal
  }
}


/* vege */

function solution_toggle(id){
  eval("$('#"+id+"').toggle();");
}

var ajaxstopbind=false;
function ajax_wait() {
  if (!ajaxstopbind) {
    $().ajaxStop($.unblockUI);//csak egyszer
    ajaxstopbind = true;
  }
  $.blockUI({
    message: "<h1><center><img src=\"images/zoom/spinner.gif\" alt=\"\"></center>Kérlek várj!</center></h1>",
    applyPlatformOpacityRules: false
  });
}

function ws_pos(spos, page)
{
  if (typeof ws_pager == 'undefined') return;//hiba
  problem_per_page = ws_pager[spos].problem_per_page;
  var filled = ws_filled[spos];
  var wsid = "ws_"+spos;
  var oldpage = null;
  if ( (typeof page == 'undefined') && (typeof ws_pager[spos].page != 'undefined') ) page = ws_pager[spos].page; else {
    if (typeof page == 'undefined') page = 1;
    //alert(page);
    if (typeof ws_pager[spos] != 'undefined') oldpage = ws_pager[spos].page;
    ws_pager[spos].page = page;
  }
  if (oldpage != page) {
    $('#'+wsid+'_'+oldpage).hide();
    $('#'+wsid+'_'+page).show();//ajax után jól jön
  }
  var pageid = wsid+'_'+page;
  var posid = pageid+'_pos';
  var p = $('#'+posid);
  var html = "<table cellspacing=\"0\" cellpadding=\"0\"><tr>";

  var problempage;
  var problempageid;
  var oc;
  var j;
  var backcolor;
  //alert(ws_filled[1]);
  for (var i = 0; i < filled.length; i++)
  {
    problempage = Math.ceil((i+1)/problem_per_page);
    var visiblepages=(problempage==page)?" pager_visible_pages":"";
    problempageid = wsid+"_"+problempage;
    j=i+1;
    oc = "ws_pos('"+spos+"','"+problempage+"');window.location='#ws_rel_"+spos+"_"+j+"';return false;";
    if (filled[i] == 3) {
      stateclass = " ws_state_good";
      backcolor = "#00e00a";
    } else if (filled[i] == 2) {
      backcolor = "#f83e2f";
      stateclass = " ws_state_bad";
    } else if (filled[i] == 1) {
      backcolor = "#ffd100";
      stateclass = " ws_state_set";
    } else {
      backcolor = "#35B8FF";
      stateclass = "";
    }
    html += "<td align=\"center\" height=\"15\" width=\"19\" class=\"pager"+visiblepages+stateclass+"\"><a href=\"#\" onclick=\""+oc+"\">"+j+"</a></td>";
  }
  html += "</tr></table>";
  if (filled.length > 1) p.html(html);//csak ha 1nél nagyobb
}

function ws_set_filled(pid, state) {
/*
  Beállítja a feladat gombján a színezést (alap, kész, jó, rossz)
  hogy melyik a gombja azt a globális tömbből tudja, amit a problem.xsl-ben állítunk be a feladatok generálásánál.
*/
  if (typeof ws_pagermap == 'undefined') return;
  if (typeof ws_pagermap["p_"+pid] == 'undefined') return;
  var map = ws_pagermap["p_"+pid];
  ws_filled[map.spos][map.index] = state;
  ws_pos(map.spos);
}

function fakeradio_select(id,value) {
/*
  egy fake radiot beállít a megadott értékre
  input: egy jquery object. (egy input)
  
  a fakeradio_+id+_+value class al rendelkezo elemet kiveve minden classbelit kikapcsol, azt meg be.
  
  a value egyszavas, classname nek valid karaktereket tartalmazó string!
  
*/
  var oldval=$('#fakeradio_'+id).val();
  if (oldval==value) return;

  $('#fakeradio_'+id).val(value);
  //spanokon vegigmegyunk. ha tartalmazza a classname et, akkor bejelolo fuggveny, kulonben kijelolo fuggveny.
  $('.fakeradio_'+id).each(function(i) {
    var img=$(this).find('img.fakeradio_img');
    if ($(this).hasClass('fakeradio_'+id+'_'+value)) {
      var src="_on";
    } else var src="_off";

    var newsrc=img.attr('src').replace(/(^.*)_(on|off)(\..*)/,"$1"+src+"$3");
    img.attr('src',newsrc);
  });
  
  if (eval('typeof fakeradio_'+id+'_change') == 'function') eval('fakeradio_'+id+'_change(value)');
  
}

function stripamp(s) {
  return s.replace(/&amp;/g,"&");
  
}
function pict_tip_over(obj){
  $(obj).prev().show().css({left:$(obj).position().left+'px',top:$(obj).position().top+15+'px'});
}
function pict_tip_out(obj){
  $(obj).prev().hide();
}


function trim(str, chars) {
  return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function prepareTextBoxes(){  
 if (!document.getElementsByTagName) return;  
 var oi=0;  
 var thisObj;  
 var objs = document.getElementsByTagName("input");  
  
 for (oi=0;oi < objs.length;oi++) {  
  thisObj = objs[oi];  
  if(thisObj.getAttribute('type') == 'text'){  
   thisObj.className = 'input_text ' + thisObj.className;  
  }  
 }  
} 

function showM3D(path) {
  var width = 1005;
  var height = 630;

  var xpos = Math.round((window.screen.width / 2) - (width / 2));
  var ypos = Math.round((window.screen.height / 2) - (height / 2));

  if ( xpos < 0 ) { xpos = 0; }
  if ( ypos < 0 ) { ypos = 0; }

  var win_dimensions = "height=" + height + ",width=" + width;

  m3dWindow = window.open(path, "m3dWindow", win_dimensions + ",resizable=1,scrollbars=no");

  if (m3dWindow.moveTo) m3dWindow.moveTo(xpos, ypos);

  if (window.focus) m3dWindow.focus();
}

function showFlash(path, wid, hei)
{
  var xpos = Math.round((window.screen.width / 2) - (wid / 2));
  var ypos = Math.round((window.screen.height / 2) - (hei / 2));

  if ( xpos < 0 ) { xpos = 0; }
  if ( ypos < 0 ) { ypos = 0; }

  var win_dimensions = "height=" + hei + ",width=" + wid;

  m3dWindow = window.open(path, "m3dWindow", win_dimensions + ",resizable=0,scrollbars=no");

  if (m3dWindow.moveTo)
    m3dWindow.moveTo(xpos, ypos);

  if (window.focus)
    m3dWindow.focus();
}

function pr_object(m) {
  var s = '';
  if (typeof m != 'object') s += m; else {
    for (i in m) {
      s += i + ': ' + m[i] + "\n";
    }
    
  }
  return s;
}


if( btoa == undefined ) {
  var b64ec = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var btoa = function( str ) {
    var out = "", i = 0, len = str.length;
    while( i < len ) {
    var c1 = str.charCodeAt( i++ ) & 0xff;
    if( i == len ) {
      out += b64ec.charAt( c1 >> 2 )
        + b64ec.charAt( ( c1 & 0x3 ) << 4 )
        + "==";
      break;
    }
    var c2 = str.charCodeAt( i++ );
    if( i == len ) {
      out += b64ec.charAt( c1 >> 2 )
        + b64ec.charAt( ( ( c1 & 0x3 ) << 4 ) | ( ( c2 & 0xF0 ) >> 4 ) )
        + b64ec.charAt( ( c2 & 0xF ) << 2 )
        + "=";
      break;
    }
    var c3 = str.charCodeAt( i++ );
    out += b64ec.charAt( c1 >> 2 )
      + b64ec.charAt( ( ( c1 & 0x3 ) << 4 ) | ( ( c2 & 0xF0 ) >> 4 ) )
      + b64ec.charAt( ( ( c2 & 0xF ) << 2 ) | ( ( c3 & 0xC0 ) >> 6 ) )
      + b64ec.charAt( c3 & 0x3F );
    }
    return out;
  }
}
